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:

/**
   * @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;
  }

So you pass in a content_type name and the method will return an array of fields that have been created by us, so not the default Drupal fields.

I cant figure out how to write a Unit Test for this method, can someone please help?

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, privacy policy and cookie policy

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