PHPUnit documentation on mock is full of information on all the possibilities. you can make a method throw an exception, you can verify successive calls to a method.). There are of course more options on what you can assert and mock (e.g. We will use these and the amazing dg/bypass-finals library to allows us to mock final classes with just a few lines. This will perform an assertion that the call has been made once. Because PHPUnit is such a great tool, it allows us to write custom extensions. It means we can define what each method should return for a given set of parameters.įurthermore, when testing createPost, we prefix the method mocking by a call to ->expects($this->once()). When testing getPost, we mock the behaviour of postRepository using ->method(.)->with(.)->willReturn(.). $this->entityManager->expects($this->once()) $this->expectException(\RuntimeException::class) Public function testGetPost_PostNotFound(): void $post = $this->service->getPost(self::POST_ID) $this->service = new PostService($this->entityManager, $this->postRepository) $this->entityManager = $this->createMock(EntityManagerInterface::class) we can override the behaviour we want for each public method postRepository = $this->createMock(PostRepository::class) public methods are not doing anything by default (they usually simply returns null) Most mocking frameworks (including PHPUnit) works in a similar way that what we did when we created our own mocks: This method takes the name of the class as an argument, and returns a mock version of that class. This time, we will use the createMock method from PHPUnit to create our mocks. Throw new \RuntimeException('Post not found') That becomes even more obvious if you think about trying to create these objects. These are both services, so they should be mocked, instead of created manually. $post = $this->postRepository->find($id) Other than the missing constructor arguments, the test looks happy But somehow, we need to pass the builder an EntityManagerInterface and a DinosaurFactory. Public function createPost(Post $post): void one to retrieve a post from the DB entityManager = $entityManager It also has two public methods that we will want to test : This class takes as dependencies a doctrine entity manager and a repository. Let's reuse our example from the previous article of the PostService class. PHPUnit comes with some mocking mechanism, so this can be a good place to start! Case study Most developers use mocking tools or frameworks to avoid this issue. However, writing custom mocks takes time and can generate a lot of code once your code base starts to grow. As we've seen in the previous article, writing your own mocks is certainly a good way to understand how mocking works and why it's a powerful tool in the context of unit tests.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |