如何对多个样本执行PHPunit测试

时间:2019-02-19 10:27:12

标签: php laravel phpunit laravel-nova phpunit-testing

我想测试一组路由,看看它们是否全部抛出

  

AuthenticationException

$routes = [
            'bla/bla/bloe',
            'bla/bla/blie',
             etc..
          ];

public function test_not_alowed_exception(){
    foreach ($routes as $route){
       $this->assertTrowsAuthenticationError($route);
    }
}

public function assertTrowsAuthenticationError($url): void {
    // Tell PHPunit we are expecting an authentication error.
    $this->expectException(AuthenticationException::class);
    // Call the Url while being unauthenticated to cause the error.
    $this->get($url)->json();
}

我的代码在第一次迭代中运行良好,但是由于异常,测试在第一次迭代后停止运行。

问题:

  1. 我测试异常。
  2. 已成功引发异常。
  3. PHPUnit停止测试。 <-这就是例外。
  4. 新的迭代应从下一个URL开始。这不会发生。

由于php设计的第一个异常会停止脚本,因此如何遍历一组URL来测试它们的AuthenticationException?

1 个答案:

答案 0 :(得分:3)

异常将以异常结束代码执行的相同方式结束测试。每个测试只能捕获一个异常。

通常,当您需要使用不同的输入多次执行相同的测试时,应使用数据提供程序。

这是您可以做的:

public function provider() {
      return [
        [ 'bla/bla/bloe' ],
        [ 'bla/bla/blie' ],
         etc..
      ];
}

/**
  *  @dataProvider provider
  */
public function test_not_alowed_exception($route){
     $this->assertTrowsAuthenticationError($route);
}

public function assertTrowsAuthenticationError($url): void {
    // Tell PHPunit we are expecting an authentication error.
    $this->expectException(AuthenticationException::class);
    // Call the Url while being unauthenticated to cause the error.
    $this->get($url)->json();
}
相关问题