【问题标题】:PHPUnit Test Exception and AssertEqualsPHPUnit 测试异常和 AssertEquals
【发布时间】:2017-03-12 14:42:16
【问题描述】:

我实际上是在尝试理解 PHPUNIT 和使用 PHP 进行单元测试。

我有一个经典的划分方法。

 public function divide($firstNumber, $secondNumber){
    if( !is_numeric($firstNumber) ||  !is_numeric($secondNumber) ){
        throw new Exception("Not a number") ; 
    }
    if(  $secondNumber == 0 ) throw new Exception("Can't divide by zero") ; 

    return $firstNumber/$secondNumber ; 
}

如您所见,它可以返回数字或异常。 这是我使用的 testDivide 代码。

 /**
 * @dataProvider diviserDateProvider
 * @covers MyTools::diviser     
 */
public function testDivide($firstNumber, $secondNumber, $expected) {
    $myToolsClasse = new MyTools();
    $this->assertEquals($expected, $myToolsClasse->diviser($firstNumber, $secondNumber));



}

public function diviserDateProvider() {
    return array(
        array(1, 0, new Exception("Can't divide by zero")),
        array(1, 2, 0.5),
        array("", "", 0.5)
    );
}

如您所见,有一个具有多个测试值的 DataProvider。 问题是我必须排除/断言一个例外,这是最好的方法吗?

我应该在我的 testDivide 代码中使用 @exceptException 并使用 try catch 吗? 谢谢你的帮助 祝你今天过得愉快!

【问题讨论】:

    标签: php unit-testing testing phpunit


    【解决方案1】:

    试试这个

    $this->expectException(\Exception::class);
    $this->expectExceptionMessage('Expected Exception Message');
    

    https://phpunit.de/manual/6.5/en/writing-tests-for-phpunit.html#writing-tests-for-phpunit.exceptions.examples.ExceptionTest.php

    【讨论】:

      【解决方案2】:

      使用 PHPUnit 测试异常的 best practice 是在测试方法的代码中使用 expectException()

      【讨论】:

      • 我确实使用了@ExpectException 注释,但我需要一个 testMethod,我可以在其中使用 AssertEquals 来处理不会引发异常的 2 个值。并且 1 断言会引发异常......那么,是否可以在同一个测试方法中断言和“断言”?或者我应该把他们分开......
      • 我建议使用expectException()方法,而不是@expectedException注解。
      • @Joe,您可以将它们放在同一个测试中,但是您当然需要注意(并记住)它们的顺序很重要(应该在 之后抛出异常> 断言,因为它阻止方法继续执行)。这在很大程度上取决于您正在测试的方面是什么,但是(对于 PHPUnit 目前的工作方式)是不可取的,我建议用两种不同的方法测试断言和异常。
      猜你喜欢
      • 1970-01-01
      • 2016-04-27
      • 2014-07-07
      • 2015-10-17
      • 1970-01-01
      • 2011-03-29
      • 2012-03-20
      • 2018-03-31
      • 2020-12-21
      相关资源
      最近更新 更多