The practice of replacing an object with a test double that verifies expectations, for instance asserting that a method has been called, is referred to as mocking.
Lets assume we have SomeService to test.
class SomeService
{
private $repository;
public function __construct(Repository $repository)
{
$this->repository = $repository;
}
public function methodToTest()
{
$this->repository->save('somedata');
}
}
And we want to test if methodToTest
really calls save
method of repository. But we don't want to actually instantiate repository (or maybe Repository
is just an interface).
In this case we can mock Repository
.
use PHPUnit\Framework\TestCase as TestCase;
class SomeServiceTest extends TestCase
{
/**
* @test
*/
public function testItShouldCallRepositorySavemethod()
{
// create an actual mock
$repositoryMock = $this->createMock(Repository::class);
$repositoryMock->expects($this->once()) // test if method is called only once
->method('save') // and method name is 'save'
->with('somedata'); // and it is called with 'somedata' as a parameter
$service = new SomeService($repositoryMock);
$service->someMethod();
}
}