Jay Rajput
Jay Rajput

Reputation: 1898

phpunit custom teardown specific to my test

I have some setup specific to my test in a class. Since it is specific to my test, I have added to it to the top of my test function. The cleanup is added to the end of the test function. The problem when the test fails and the cleanup does not gets executed. Is there a PHPUnit way to specify a custom teardown specific to my test function. I looked at the PHPUnit manual which specifies teardownAfterClass and tearDown, but both does not solve my problem. The function teardownAfterClass will run only once at the end of the class. The function teardown runs after each test, but I do not want to do any cleanup if my specific test function was not executed.

What is the PHPUnit way of creating custom teardown function for my test?

Here is the code which I use to make sure that the cleanup specific to the test always happen, but it is ugly as it needs to put the actual test in a separate function and needs try/catch block. Is there is a PHPUnit specific way to handle it? Something like dataProvider specific to function will be great, which always gets executed after the test irrespective of failure or success.

class testClass  {

    public function test1() {
        self::setupSpecificToTest1();
        try {
            // actual test without cleanup
            $this->_test1();

        } catch (Exception $e) {
            self::cleanupSpecificToTest1();
            throw $e;
        }
        self::cleanupSpecificToTest1();
    }

    public function test2() {
        // some code which does not need any setup or cleanup
    }

    private function _test1() {
        // some test code
    }
}

Upvotes: 2

Views: 1851

Answers (2)

BVengerov
BVengerov

Reputation: 3007

Implement intelligent tearDown (it's closer to PHPUnit's approach to running tests)

You can check for the specific test name inside tearDown method to alternate its behaviour accordingly. Getting test name can be done via $this->getName() in the test class.

Try something like:

...
public function test1() { ... }

public function test2() { ... }

public function tearDown()
{
    if ($this->getName() === 'test1')
    {
        // Do clean up specific to test1
    }
    parent::tearDown();
}

Upvotes: 2

user7365049
user7365049

Reputation:

I have tried this, it worked for me after my test.

public function tearDown()
    {
        $this->webDriver->close();
    }   

Upvotes: -1

Related Questions