Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPUnit: Skipping All Tests When One Fails

Tags:

php

phpunit

All of the tests in my test case depend on the first test passing. Now I know I can add the @depends annotation to the rest of the tests, but I'm looking for a shortcut to adding the annotation to every other test method. Is there a way to tell PHPUnit, "Skip the rest of the tests if this one fails"?

like image 525
mellowsoon Avatar asked Aug 08 '26 21:08

mellowsoon


2 Answers

You can add that particular test to your setup() method. This will make all tests failing this test get skipped, e.g.

public function setup()
{
    $this->subjectUnderTest = new SubjectUnderTest;
    $this->assertPreconditionOrMarkTestSkipped();
}

public function assertPreconditionOrMarkTestSkipped()
{
    if ($someCondition === false) {
        $this->markTestSkipped('Precondition is not met');
    }
}
like image 89
Gordon Avatar answered Aug 10 '26 14:08

Gordon


Similar to Gordon's answer but without moving the first test into setUp, a similar method is to set a class-level property in the first test based on its success/failure and check this property in setUp. The only difference is the first test is executed just once as it is now.

private static $firstPassed = null;

public function setup() {
    if (self::$firstPassed === false) {
        self::markTestSkipped();
    }
    else if (self::$firstPassed === null) {
        self::$firstPassed = false;
    }
}

public function testFirst() {
    ... the test ...
    self::$firstPassed = true;
}
like image 22
David Harkness Avatar answered Aug 10 '26 14:08

David Harkness



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!