Search code examples
phpunit-testingtestingphpunit

Any real word example about how setUp() and tearDown() should be used in PHPUnit?


Methods setUp() and tearDown() are invoked before and after each test. But really, is there any real word example about why should I need this?

Inspecting other people tests, I always see something like:

public function setUp()
{
    $this->testsub = new TestSubject();
}

public function tearDown()
{
    unset($this->testsub);
}

public function testSomething()
{
    $this->assertSame('foo', $this->testsub->getFoo());
}

Of course, there is virtually no difference between this way and the "old" local variable way.


Solution

  • If you do every test method individually, your test code will share a lot of lines that simply create the object to be tested. This shared code can (but not SHOULD) go into the setup method.

    Anything that needs to be done to create the object to be tested then also goes into the setup method, for example creating mock objects that are injected into the constructor of the tested object.

    Nothing of this needs to be teared down because the next call to setup will initialize the class member variables with a new set of objects.

    The only thing that needs teardown is if your test leaves something behind permanently, like files that got created, or database entries. It really isn't a very good idea to write tests that do such things, but at some point you cannot abstract anymore and have to touch stuff like the harddrive, database or the real network.

    So there is a lot more setup than teardown needed, and I always delete the teardown method if there is no work to be done for this test.

    Regarding mocks, I work like this:

    private $_mockedService;
    private $_object;
    protected function setUp()
    {
        $this->_mockedService = $this->getMock('My_Service_Class');
        $this->_object = new Tested_Class($this->_mockService);
    }
    
    public function testStuff()
    {
        $this->_mockedService->expects($this->any())->method('foo')->will($this->returnValue('bar'));
        $this->assertEquals('barbar', $this->_object->getStuffFromServiceAndDouble());
    }