3

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

4
  • 1
  • 1
    @MikeB - Those will skip all further tests--not just those in the same test case as mellowsoon requested. Commented Sep 4, 2012 at 18:52
  • 2
    @DavidHarkness That's why I left it as a comment instead of an answer. OP didn't delve too much into the goal behind the request so I just threw it out there.
    – Mike B
    Commented Sep 4, 2012 at 19:33
  • I think they are looking to have the code continue into the other asserts within the test. For instance, if I am checking 3 different conditions, I would like to know that all three asserts in the test passed or failed individually, instead of having to review one, run the tests again, review the next issue, then even the third. Can PHPUnit not be instructed to do this, so all tests in the function testXXXX can be executed? Commented Sep 5, 2012 at 15:40

2 Answers 2

6

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');
    }
}
6

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.