【问题标题】:How to get result from expectException and passed test in PHPUnit?如何从expectException获取结果并在PHPUnit中通过测试?
【发布时间】:2021-10-01 16:32:43
【问题描述】:

我在 docker 中有一个使用 PHP 7.2 的应用程序,我必须使用 TDD 重新构建它。

我在购物车类中有这个方法:

public function getItem($index)
{
    if (!isset($this->items[$index])) {
        throw new \Exception('Item with index('.$index.') not exists', '404');
    }
    $this->chosenItem = $index;
    
    return $this;
}

另一个在测试类中进行测试:

public function itThrowsExceptionWhileGettingNonExistentItem(int $index): void
{
    $product = $this->buildTestProduct(1, 15000);

    $cart = new Cart();
    $cart->addProduct($product, 1);
    $cart->getItem($index);

    $this->expectException(\Exception::class);
}

当我运行 phpunit 时,我会在终端中看到这条消息:

There were 4 errors:

1) Recruitment\Tests\Cart\CartTest::itThrowsExceptionWhileGettingNonExistentItem with data set #0 (-9223372036854775807-1)
Exception: Item with index(-9223372036854775808) not exists
src\Cart\Cart.php:88
tests\Cart\CartTest.php:102

而且我在最终的 phpunit.txt 报告中没有标记出好的结果

 [ ] It throws exception while getting non existent item with data set #0

我做错了什么?线程抛出显示,但是PHPUnit测试还是失败?

【问题讨论】:

  • 这是基本的,如果你不告诉它断言一个异常,你怎么能断言一个异常?任何将被抛出的异常都不会被断言,因为你没有在它被抛出之前写断言之前......下次做一个优秀的开发人员并阅读documentation,因为它存在为此...

标签: php phpunit tdd


【解决方案1】:

您的测试的正确代码是:

public function itThrowsExceptionWhileGettingNonExistentItem(int $index): void
{
    $this->expectException(\Exception::class);

    $product = $this->buildTestProduct(1, 15000);
    $cart = new Cart();
    $cart->addProduct($product, 1);
    $cart->getItem($index);
}

您必须首先定义将发生的异常,然后之后运行将引发此异常的代码。

【讨论】:

    猜你喜欢
    • 2020-08-01
    • 2020-06-28
    • 1970-01-01
    • 2016-11-25
    • 1970-01-01
    • 1970-01-01
    • 2012-06-17
    • 1970-01-01
    • 2017-07-31
    相关资源
    最近更新 更多