PHPUnit - assertion failed but I want to continue testing

后端 未结 4 1308
余生分开走
余生分开走 2021-02-07 10:59
->assertTrue(false);
->assertTrue(true);

First assertion was failed and execution was stopped. But I want to continue the further snippet of code

4条回答
  •  囚心锁ツ
    2021-02-07 11:33

    The other answerers are correct - you really should separate out your assertions into separate tests, if you want to be able to do this. However, assuming you have a legitimate reason for wanting to do this... there is a way.

    Phpunit assertion failures are actually exceptions, which means you can catch and throw them yourself. For example, try this test:

    public function testDemo()
    {
        $failures = [];
        try {
            $this->assertTrue(false);
        } catch(PHPUnit_Framework_ExpectationFailedException $e) {
            $failures[] = $e->getMessage();
        }
        try {
            $this->assertTrue(false);
        } catch(PHPUnit_Framework_ExpectationFailedException $e) {
            $failures[] = $e->getMessage();
        }
        if(!empty($failures))
        {
            throw new PHPUnit_Framework_ExpectationFailedException (
                count($failures)." assertions failed:\n\t".implode("\n\t", $failures)
            );
        }
    }
    

    As you can see, it tries two assertions, both of which fail, but it waits until the end to throw all of the failure output messages as a single exception.

提交回复
热议问题