5

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

3
  • why do you need the mock in there? cant you just set it up in the regular setup method or in the test? if you are going to setup expectations for the mock, you dont want it to be created only once, but for each test. Commented Oct 18, 2011 at 10:42
  • mocked_object's methods will always return the same results, so that's why I thought it's better to instantiate it only once... Anyway, I could create it in the setup method, but I would like to know if it could be created in the setUpBeforeClass too. Commented Oct 18, 2011 at 10:50
  • 2
    Not sure if it's possible, but I'd argue its bad practise, since you want a clean stub for each test for isolation. Commented Oct 18, 2011 at 10:58

1 Answer 1

5

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'));
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.