I have been reading the test doubles section of phpunit manual to figure out if it is possible to create an stub from an interface. I need to fake an call to a method from an object which implements an interface but I don't want to create a fake class for that. Is it a way to create an instance of object that implements an interface without actually having a class definition of such an object?
The code below isn't working but may be helpful to understand what I am trying to achieve, Thanks in advance guys
/**
* @test
* @expectedException InvalidArgumentException
*/
public function searchAlbumThrowExceptionWhenDataBaseConnectionFailed(){
$albumRepositoryStub = $this->getMock('AlbumFinder\Repository\AlbumRepositoryInterface');
$albumRepositoryStub->method('fetchPage')
->will( $this->throwException(new \Exception()));
//code
}
For this to work, you need that the interface is autoloaded. Check that by calling:
$this->assertTrue(interface_exists('AlbumFinder\Repository\AlbumRepositoryInterface'));
just at the start of the test.
If the interface loads, check that the method name is correct. Other than that it should work...
I have found the problem with my code. I was missing the 'expects' method call when mocking the interface method. This is the code that is working for me now: $albumRepositoryStub = $this->getMock('AlbumFinder\Repository\AlbumRepositoryInterface');
$albumRepositoryStub->expects($this->any())
->method('fetchPage')
->will( $this->throwException(new \Exception()));