From bc34a961879ad6b3c657ca31a3d8a55a6d03f91e Mon Sep 17 00:00:00 2001 From: Oliver Davies Date: Mon, 22 Jan 2024 18:07:07 +0000 Subject: [PATCH] Mock loadByProperties, return mock nodes, add ...assertions --- .../src/Unit/PostNodeRepositoryUnitTest.php | 38 ++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/web/modules/custom/example/tests/src/Unit/PostNodeRepositoryUnitTest.php b/web/modules/custom/example/tests/src/Unit/PostNodeRepositoryUnitTest.php index 21c91f8..b4e3fac 100644 --- a/web/modules/custom/example/tests/src/Unit/PostNodeRepositoryUnitTest.php +++ b/web/modules/custom/example/tests/src/Unit/PostNodeRepositoryUnitTest.php @@ -2,8 +2,10 @@ namespace Drupal\Tests\example\Unit; +use Drupal\Core\Entity\EntityStorageInterface; use Drupal\Core\Entity\EntityTypeManagerInterface; use Drupal\example\Repository\PostNodeRepository; +use Drupal\node\NodeInterface; use Drupal\Tests\UnitTestCase; /** @@ -13,14 +15,48 @@ final class PostNodeRepositoryUnitTest extends UnitTestCase { /** @test */ public function it_returns_posts(): void { + $node1 = $this->createMock(NodeInterface::class); + $node1->method('bundle')->willReturn('post'); + $node1->method('getCreatedTime')->willReturn(strtotime('-1 week')); + $node1->method('label')->willReturn('Post one'); + + $node2 = $this->createMock(NodeInterface::class); + $node2->method('bundle')->willReturn('post'); + $node2->method('getCreatedTime')->willReturn(strtotime('-8 days')); + $node2->method('label')->willReturn('Post two'); + + $node3 = $this->createMock(NodeInterface::class); + $node3->method('bundle')->willReturn('post'); + $node3->method('getCreatedTime')->willReturn(strtotime('yesterday')); + $node3->method('label')->willReturn('Post three'); + + $node4 = $this->createMock(NodeInterface::class); + $node4->method('bundle')->willReturn('page'); + $node4->method('label')->willReturn('Not a post'); + $nodeStorage = $this->createMock(EntityStorageInterface::class); + $nodeStorage->method('loadByProperties')->willReturn([$node1, $node2, $node3]); $entityTypeManager = $this->createMock(EntityTypeManagerInterface::class); $entityTypeManager->method('getStorage')->with('node')->willReturn($nodeStorage); $repository = new PostNodeRepository($entityTypeManager); - $repository->findAll(); + $posts = $repository->findAll(); + + self::assertContainsOnlyInstancesOf(NodeInterface::class, $posts); + + $titles = array_map( + fn (NodeInterface $node) => $node->label(), + $posts, + ); + + self::assertCount(3, $titles); + self::assertSame( + ['Post two', 'Post one', 'Post three'], + $titles, + ); + self::assertNotContains('Not a page', $titles); } }