I want to have an mocked object in all my tests, so I try to create it in the setUpBeforeClass() method, but this method is static so getMockBuilder has to be called statically like this:
public static function setUpBeforeClass() {
self::mocked_object = self::getMockBuilder('MockedClass')
->disableOriginalConstructor()
->getMock();
}
The problem is that getMockBuilder cannot be called statically :
Argument 1 passed to PHPUnit_Framework_MockObject_MockBuilder::__construct() must be an instance of PHPUnit_Framework_TestCase, null given
Is there any chance to have the mocked object be built in the setUpBeforeClass method or do I have to build it every time before a test (in the public function setUp() method) ?
Likewise, PHPUnit mock object is a simulated object that performs the behavior of a part of the application that is required in the unit test. The developers control the mock object by defining the pre-computed results on the actions.
Stubs are used with query like methods - methods that return things, but it's not important if they're actually called. $stub = $this->createMock(SomeClass::class); $stub->method('getSomething') ->willReturn('foo'); $sut->action($stub);
Each mock object is tied to the test case instance that created it. Since setUpBeforeClass()
is a static method, it does not have an instance and cannot create mock objects.
Instead, create your mocks in setUp()
or helper methods and either assign them to instance variables or return them.
class MyServiceTest extends PHPUnit_Framework_TestCase
{
function setUp() {
$this->connection = $this->getMock('MyDatabaseConnection', array('connect', ...));
$this->connection
->expects($this->once())
->method('connect');
}
function testLogin() {
$this->connection
->expects($this->once())
->method('login')
->with('bob', 'p4ssw0rd');
$service = new MyService($this->connection);
self::assertTrue($service->login('bob', 'p4ssw0rd'));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With