2

I have a method of a class that returns me the list of fields that have been created outside of core Drupal. The method is the following.

/**
   * @param $contentType
   * @return array $fields
   */
  public function getContentTypeFields($contentType) {
    /** @var \Drupal\Core\Entity\EntityFieldManagerInterface $entityManager */
    $entityManager = \Drupal::service('entity_field.manager');
    $fields = array();

    if (!empty($contentType)) {
      $fields = array_filter(
        $entityManager->getFieldDefinitions('node', $contentType),
        function ($fieldDefinition) {
          return $fieldDefinition instanceof FieldConfigInterface;
        }
      );
    }

    return $fields;
  }

It accepts a content type name and returns an array of fields that aren't the default Drupal fields.

How can I write a unit Test for this method?

1 Answer 1

1

Resurrecting this. The first method would be to include the EntityFieldManager as an argument to your function or constructor, so you can send a mock object in.

The second would be to look at some of the tests in core. Specifically core/tests/Drupal/Tests/Core/Config/Entity/ConfigEntityStorageTest.php where the container is mocked and dependencies set up.

$container = new ContainerBuilder();
$container->set('entity_type.manager', $entity_type_manager->reveal());
...
\Drupal::setContainer($container);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.