我有一个应用程序在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;
}
和Test Class中的Test:
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) RecruitmentTestsCartCartTest::itThrowsExceptionWhileGettingNonExistentItem with data set #0 (-9223372036854775807-1)
Exception: Item with index(-9223372036854775808) not exists
srcCartCart.php:88
testsCartCartTest.php:102
和我没有一个好的结果标记在最后的phpunt .txt报告
[ ] It throws exception while getting non existent item with data set #0
我做错了什么?抛出并显示线程,但PHPUnit测试仍然失败?
正确的测试代码是:
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);
}
必须先定义异常将发生,然后在之后定义运行将抛出此异常的代码。