如何从 expectException 中获取结果并在 PHPUnit 中通过测试?
How to get result from expectException and passed test in PHPUnit?
我在 docker 中有一个应用 PHP 7.2,我必须使用 TDD 重建它。
我在购物车里有这个方法Class:
public function getItem($index)
{
if (!isset($this->items[$index])) {
throw new \Exception('Item with index('.$index.') not exists', '404');
}
$this->chosenItem = $index;
return $this;
}
另一个在测试 Class 中测试:
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
我做错了什么?线程抛出显示了,但是PHP单元测试还是失败了?
您的测试的正确代码是:
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);
}
您必须首先定义将发生的异常,然后然后 运行定义将抛出该异常的代码。
我在 docker 中有一个应用 PHP 7.2,我必须使用 TDD 重建它。
我在购物车里有这个方法Class:
public function getItem($index)
{
if (!isset($this->items[$index])) {
throw new \Exception('Item with index('.$index.') not exists', '404');
}
$this->chosenItem = $index;
return $this;
}
另一个在测试 Class 中测试:
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
我做错了什么?线程抛出显示了,但是PHP单元测试还是失败了?
您的测试的正确代码是:
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);
}
您必须首先定义将发生的异常,然后然后 运行定义将抛出该异常的代码。