Creating mock classes usually involves configuring method call expectations on the mocks/test doubles.
E.g. in 'vanilla' PHPUnit we can stub a method call and set an expectations like so:
$stub->expects($this->any())->method('doSomething')->willReturn('foo');
In the Mockery mock object framework, we get the API like this:
$mock->shouldReceive('doIt')->with(m::anyOf('this','that'))->andReturn($this->getSomething());
Expectations like these, are often wired in the set-up phase of a test-suite, e.g. the setUp()
method of \PHPUnit_Framework_TestCase
.
Expectations like the ones presented above would break the test if they are not fulfilled. Consequently, making the expectations to be actual assertions.
This leads to the situation where we have assertions (assertions + expectations) scattered around the test case class since we end up having actual assertions in the set-up phase of a test case as well as in individual tests.
Would it be good practice to test method call expectations in 'regular' assert..
method. This might look like that (Mockery):
public function setUp()
{
$mock = m::mock(SomeClass::class);
$mock->shouldReceive('setSomeValue');
$this->mock = $mock;
}
and later at the end of one of the test methods:
public function testSoemthing()
{
...
$this->assertMethodCalled($this->mock, 'setSomeValue');
}
assertMethodCalled
in not a method exposed by PHPUnit. It'd have to be implemented.
In short, should we treat expectation declarations as actual assertions and consequently test against them in our test methods?