Answer the question
In order to leave comments, you need to log in
What's the point of mock objects for unit testing your code?
Hello everyone, I use phpunit for tests, I ran into a misunderstanding of the meaning of mock classes and their methods.
The situation that I understand is a mock http client that returns a specific result and is tied to an external service, but what about simple classes that are not connected to the outside world?
There is a small example:
<?php
class SomeClass
{
public function doSomething(): string
{
return 'foo';
}
}
<?php
use PHPUnit\Framework\TestCase;
class StubTest extends TestCase
{
public function testStub(): void
{
// Создать заглушку для класса SomeClass.
$stub = $this->createMock(SomeClass::class);
// Настроить заглушку.
$stub->method('doSomething')
->willReturn('foo');
// Вызов $stub->doSomething() теперь вернёт 'foo'.
$this->assertSame('foo', $stub->doSomething());
}
}
Answer the question
In order to leave comments, you need to log in
The point of mocks is to emulate objects with certain behavior.
The most banal example, besides http requests, is the emulation of incorrect objects.
Let's say you have a service that processes some object. The object is written well, with data validation, and its behavior is correct. But in order for you to write a quality service, it should not rely on the fact that another object behaves correctly. It must additionally check the boundary situations. And of course, you need to write tests for such cases, but how can you write them if the object under test is written in such a way that it behaves correctly? This is where moki come to the rescue.
phpunit has functionality to calculate code coverage by tests- try on some relatively small module to achieve 100% code coverage with tests - you will definitely have to use tricky mocks that emulate non-standard behavior of objects.
PS If you're new to unit tests, misunderstanding mocks is normal. If you strive to write reliable code, with high-quality code coverage by tests (the most difficult thing here is to predict all the bad cases that will try to break your code) - understanding will come.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question