Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an mocked object in phpunit's setUpBeforeClass method?

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) ?

like image 381
Adi Fatol Avatar asked Oct 18 '11 10:10

Adi Fatol


People also ask

What is mock test PHPUnit?

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.

What is stub in PHPUnit?

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);


1 Answers

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'));
    }
}
like image 149
David Harkness Avatar answered Sep 22 '22 17:09

David Harkness