【问题标题】:How can I perform PHPunit test for multiple exeptions如何对多个异常执行 PHPunit 测试
【发布时间】:2019-07-12 19:47:08
【问题描述】:

我想测试一个路由数组,看看它们是否都抛出了

身份验证异常

$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 设计的第一个异常停止了脚本?

【问题讨论】:

  • 由于我不是母语人士,这个问题可能不清楚。如果您有任何问题,请发表评论。我会尽力澄清。我会上网一段时间!
  • 您是否尝试过使用数据提供者?有关文档,请参阅phpunit.readthedocs.io/en/8.0/…
  • 感谢您的评论,虽然我认为问题不存在,但我会测试一下!
  • 好吧,如果您认为使用数据提供者没有帮助,您应该进一步解释问题出在哪里

标签: php laravel laravel-nova phpunit


【解决方案1】:

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

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

你可以这样做:

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();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-06
    • 2014-07-07
    • 2019-06-02
    • 2014-08-21
    • 2015-10-17
    • 2016-04-27
    • 1970-01-01
    相关资源
    最近更新 更多