【发布时间】: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,因为它存在为此...