function MediaCreationTest::testMediaEntityCreation

Same name in other branches
  1. 9 core/modules/media/tests/src/Kernel/MediaCreationTest.php \Drupal\Tests\media\Kernel\MediaCreationTest::testMediaEntityCreation()
  2. 8.9.x core/modules/media/tests/src/Kernel/MediaCreationTest.php \Drupal\Tests\media\Kernel\MediaCreationTest::testMediaEntityCreation()
  3. 10 core/modules/media/tests/src/Kernel/MediaCreationTest.php \Drupal\Tests\media\Kernel\MediaCreationTest::testMediaEntityCreation()

Tests creating a media item programmatically.

File

core/modules/media/tests/src/Kernel/MediaCreationTest.php, line 66

Class

MediaCreationTest
Tests creation of media types and media items.

Namespace

Drupal\Tests\media\Kernel

Code

public function testMediaEntityCreation() : void {
    $media = Media::create([
        'bundle' => $this->testMediaType
            ->id(),
        'name' => 'Unnamed',
        'field_media_test' => 'Nation of sheep, ruled by wolves, owned by pigs.',
    ]);
    $media->save();
    $this->assertNotInstanceOf(MediaInterface::class, Media::load(rand(1000, 9999)));
    $this->assertInstanceOf(MediaInterface::class, Media::load($media->id()));
    $this->assertSame($this->testMediaType
        ->id(), $media->bundle(), 'The media item was not created with the correct type.');
    $this->assertSame('Unnamed', $media->getName(), 'The media item was not created with the correct name.');
    $source_field_name = $media->bundle->entity
        ->getSource()
        ->getSourceFieldDefinition($media->bundle->entity)
        ->getName();
    $this->assertSame('Nation of sheep, ruled by wolves, owned by pigs.', $media->get($source_field_name)->value, 'Source returns incorrect source field value.');
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.