如何为多个异常执行PHPunit测试

问题描述 投票:0回答:1

我想测试一系列路线,看看它们是否全部抛出

的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开始新的迭代。这不会发生。

我如何循环遍历一组URL以测试它们的AuthenticationException?,因为php设计的第一个异常会停止脚本?

php laravel phpunit laravel-nova phpunit-testing
1个回答
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();
}
© www.soinside.com 2019 - 2024. All rights reserved.