diff --git a/backend/tests/Unit/Comment/UseCases/CreateCommentTest.php b/backend/tests/Unit/Comment/UseCases/CreateCommentTest.php new file mode 100644 index 0000000..f35f8e8 --- /dev/null +++ b/backend/tests/Unit/Comment/UseCases/CreateCommentTest.php @@ -0,0 +1,138 @@ +now = new DateTimeImmutable( + '2026-05-06T12:00:00', + new DateTimeZone('UTC'), + ); + $this->commentRepo = new FakeCommentRepository; + $this->postRepo = new FakePostRepository; + $this->clock = new FakeClock($this->now); + $this->useCase = new CreateComment( + $this->commentRepo, + $this->postRepo, + $this->clock, + ); + } + + private function seedPost(): int + { + $post = $this->postRepo->create(new CreatePostDto( + userId: 1, + title: 'Some Post', + body: 'Body.', + createdAt: $this->now, + )); + + return $post->getId(); + } + + public function test_zero_post_id_throws_bad_request(): void + { + $this->expectException(BadRequestException::class); + $this->useCase->execute(new CreateCommentRequest( + postId: 0, + userId: 1, + body: 'hi', + )); + } + + public function test_zero_user_id_throws_bad_request(): void + { + $postId = $this->seedPost(); + $this->expectException(BadRequestException::class); + $this->useCase->execute(new CreateCommentRequest( + postId: $postId, + userId: 0, + body: 'hi', + )); + } + + public function test_null_body_throws_bad_request(): void + { + $postId = $this->seedPost(); + $this->expectException(BadRequestException::class); + $this->useCase->execute(new CreateCommentRequest( + postId: $postId, + userId: 1, + body: null, + )); + } + + public function test_blank_body_throws_bad_request(): void + { + $postId = $this->seedPost(); + $this->expectException(BadRequestException::class); + $this->useCase->execute(new CreateCommentRequest( + postId: $postId, + userId: 1, + body: ' ', + )); + } + + public function test_unknown_post_throws_domain_exception(): void + { + $this->expectException(DomainException::class); + $this->useCase->execute(new CreateCommentRequest( + postId: 999, + userId: 1, + body: 'hi', + )); + } + + public function test_valid_create_returns_comment(): void + { + $postId = $this->seedPost(); + $created = $this->useCase->execute(new CreateCommentRequest( + postId: $postId, + userId: 5, + body: ' Hello world ', + )); + + $this->assertSame($postId, $created->getPostId()); + $this->assertSame(5, $created->getUserId()); + $this->assertSame('Hello world', $created->getBody()); + $this->assertEquals($this->now, $created->getCreatedAt()); + } + + public function test_created_comment_is_findable(): void + { + $postId = $this->seedPost(); + $created = $this->useCase->execute(new CreateCommentRequest( + postId: $postId, + userId: 5, + body: 'Hello', + )); + + $found = $this->commentRepo->find($created->getId()); + $this->assertNotNull($found); + $this->assertSame('Hello', $found->getBody()); + } +}