Skip to content

Instantly share code, notes, and snippets.

@kazukomurata
Created December 3, 2021 02:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kazukomurata/20b31c6e6a20dca3ec51476ba90b2633 to your computer and use it in GitHub Desktop.
Save kazukomurata/20b31c6e6a20dca3ec51476ba90b2633 to your computer and use it in GitHub Desktop.
Drupalの正当なKernelテスト
<?php
namespace Drupal\Tests\example_module\Kernel;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\KernelTests\KernelTestBase;
use Drupal\node\Entity\Node;
use Drupal\node\Entity\NodeType;
use Drupal\taxonomy\Entity\Term;
use Drupal\taxonomy\Entity\Vocabulary;
use Drupal\Tests\ConfigTestTrait;
use Drupal\Tests\node\Traits\NodeCreationTrait;
use Drupal\Tests\user\Traits\UserCreationTrait;
/**
* Provides example test.
*/
class ExampleTaihennaTest extends KernelTestBase {
use ConfigTestTrait;
use NodeCreationTrait;
use UserCreationTrait;
/**
* Modules to enable.
*
* @var array
*/
protected static $modules = [
'system',
'node',
'taxonomy',
'user',
'text',
'field',
'filter',
];
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->installEntitySchema('node');
$this->installEntitySchema('taxonomy_term');
$this->installConfig('filter');
}
/**
* Tests example.
*/
public function testExample() {
// タクソノミー作成.
$vocabulary = Vocabulary::create(['vid' => 'tags']);
$vocabulary->save();
// Node type作成.
$content_type = NodeType::create([
'type' => 'article',
'name' => 'Article test',
]);
$content_type->save();
// bodyフィールド追加.
FieldStorageConfig::create([
'field_name' => 'field_body',
'entity_type' => 'node',
'type' => 'text_with_summary',
])->save();
$field_body = FieldConfig::create([
'entity_type' => 'node',
'field_name' => 'field_body',
'bundle' => 'article',
]);
$field_body->save();
// tagsフィールド追加.
FieldStorageConfig::create([
'field_name' => 'field_tags',
'entity_type' => 'node',
'type' => 'entity_reference',
'settings' => [
'target_type' => 'taxonomy_term',
],
])->save();
$field_tags = FieldConfig::create([
'entity_type' => 'node',
'field_name' => 'field_tags',
'bundle' => 'article',
]);
$field_tags->save();
// ユーザの作成.
$user = $this->setUpCurrentUser();
// タグのターム作成.
$term = Term::create(['vid' => 'tags', 'name' => 'タグテスト']);
$term->save();
$node = Node::create([
'type' => 'article',
'field_tags' => $term->id(),
'title' => 'test',
'uid' => $user->id(),
]);
$node->save();
$result_terms = $node->get('field_tags')->referencedEntities();
$this->assertEquals('タグテスト', reset($result_terms)->label());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment