1

I'm trying to write some PHPUnit Kernel tests that use a custom content type which seem to work until I try to reference fields on the content type. I'm guessing the content type isn't being imported from config. Is there a correct way to do this?

Example code which works in drush php but does not work in phpunit:

  public function createAction() {
    $storage = $this->container->get('entity_type.manager')->getStorage('node');
    $entity = $storage->create(['type' => 'action']);
    $entity->set('title', 'test');
    $entity->set('field_lookup_type', 'address');
    $entity->save();
    return $entity;
  }

The error from phpunit is "InvalidArgumentException: Field field_lookup_type is unknown."

2

That wont do it. You either need to create a test module that has YAML configs to do this, or script in the changes in the test setup method. The latter method is longer, but frees you from having to maintain copies of YAML configs in an additional module(s). Here is an example.

  public function setUp() {
    parent::setUp();
    $this->entityTypeManager = $this->container->get('entity_type.manager');

    $this->installEntitySchema('node');
    $this->installEntitySchema('user');
    $this->installEntitySchema('taxonomy_term');
    $this->installSchema('node', 'node_access');
    $this->installConfig('node');
    $this->installConfig('taxonomy');
    $this->installConfig('filter');

    $this->createContentType(['type' => 'my_content_type']);

    FieldStorageConfig::create([
      'field_name' => 'field_lookup_type',
      'entity_type' => 'node',
      'type' => 'entity_reference',
      'cardinality' => 1,
      'locked' => FALSE,
      'indexes' => [],
      'settings' => [
        'handler' => 'default:taxonomy_term',
        'handler_settings' => [
          'target_bundles' => [],
          'sort' => [
            'field' => 'name',
            'direction' => 'asc',
          ],
          'auto_create' => false,
          'auto_create_bundle' => '',
        ],
      ]
    ])->save();

    FieldConfig::create([
      'field_name' => 'field_lookup_type',
      'entity_type' => 'node',
      'label' => 'My Field',
      'bundle' => 'my_content_type',
      'description' => '',
      'required' => FALSE,
      'settings' => [],
    ])->save();

This creates a node type, creates a taxonomy field, and sets the taxonomy field to that node type. This is the equivalent of loading several YAML files.

Then, either in setup or a test itself, you can:

 $node = $this->createNode(['type' => 'my_content_type', 'field_lookup_type' => 1]);

The traits to do this need to be included in your test class:

  use NodeCreationTrait,
    ContentTypeCreationTrait,

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.