How do you repeat a test in PHPUnit?

南笙酒味 提交于 2021-01-24 08:00:09

问题


I know about the "--repeat" option, but I'd rather define the repeating within the test and per test. In my unit tests there are tests I don't want to repeat, and there are tests I want to repeat more than others.

I was thinking:

protected function tearDown() {
  if (test has not been ran 3 times) {
      $this->runTest(); // Re-run the test
  }
}

This doesn't seem to work, nor does $this->run(). I've looked at the PHPUnit source code but I'm not sure. I'm guessing it's checking the test status and if it's been ran it denies running it again.


回答1:


phpunit has a repeat option within the command line runner. This works as follows for a test which repeats 3 times:

phpunit --repeat 3 myTest.php




回答2:


There's far more to running a test than setUp, run, and tearDown. For one thing, each test method is run against a new instance of the test case. Don't forget about @dataProvider and the other annotations, code coverage, etc. You really don't want to do this.

For the few cases you absolutely need it, code the loop in the test method itself.




回答3:


This is a bit of a roundabout way of doing this but it's the cleanest I could come up with:

/**
 * @dataProvider numberOfTests
 */
public function test()
{
    // Do your test
}

public function numberOfTests() 
{
    for ($i = 0; $i < 100; $i++) {
       yield [];
    }
}

The benefit of this is setUp and tearDown methods will be run for each invocation of the loop.




回答4:


I think you need to take a step back and create a test that runs your tests!

You need a loop that goes something along the lines of:

$myTest = \my\test\class();
foreach($iterations){
    $myTest->setup();
    $myTest->doTestyStuff();
    $myTest->tearDown();
}

the code you posted won't work because each test needs the setup and teardown to be run each time the test runs.




回答5:


Can this not be achieved with a do-while loop?

protected function tearDown() {
    $i = 0;
    do {
        $this->runTest(); // Re-run the test
        $i++;
    } while($i < 3);
}


来源:https://stackoverflow.com/questions/9489081/how-do-you-repeat-a-test-in-phpunit

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!