简体   繁体   English

你如何在 PHPUnit 中重复测试?

[英]How do you repeat a test in PHPUnit?

I know about the "--repeat" option, but I'd rather define the repeating within the test and per test.我知道“--repeat”选项,但我宁愿在测试和每个测试中定义重复。 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().这似乎不起作用,$this->run() 也不起作用。 I've looked at the PHPUnit source code but I'm not sure.我看过 PHPUnit 源代码,但我不确定。 I'm guessing it's checking the test status and if it's been ran it denies running it again.我猜它正在检查测试状态,如果它已经运行,它会拒绝再次运行它。

phpunit has a repeat option within the command line runner. phpunit 在命令行运行器中有一个重复选项。 This works as follows for a test which repeats 3 times:对于重复 3 次的测试,其工作原理如下:

phpunit --repeat 3 myTest.php phpunit --repeat 3 myTest.php

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.这样做的好处是每次调用循环都会运行 setUp 和 tearDown 方法。

There's far more to running a test than setUp , run , and tearDown .运行测试远不止setUpruntearDown 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.不要忘记@dataProvider和其他注释、代码覆盖率等。您真的不想这样做。

For the few cases you absolutely need it, code the loop in the test method itself.对于您绝对需要它的少数情况,请在测试方法本身中编写循环。

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 .您发布的代码将不起作用,因为每个测试都需要在每次测试运行运行设置和拆卸。

Can this not be achieved with a do-while loop?这不能通过 do-while 循环实现吗?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM