[英]Continue test after expect exception phpunit
我有代碼。
try {
$this->entityManager->beginTransaction();
$this->repo->remove($something);
$this->repoTwo->delete($something);
$this->entityManager->commit();
} catch (Exception $e) {
$this->entityManager->rollback();
throw new Exception($e->getMessage(), 0, $e);
}
現在,我想測試一下,如果數據庫中仍然有記錄,在異常之后,我該怎么做,如果測試在預期異常后無法工作?
$this->expectException(Exception::class);
$this->expectExceptionMessage('xxxx');
app(Command::class)->handle();
$this->seeInDatabase($table, [
'id' => $media->id(),
]);
我怎么能這樣做? 謝謝。
通常你可以創建兩個測試。 一個測試異常被拋出,一個依賴於第一個測試和測試記錄仍然存在,但在這種情況下,數據庫將在每次測試之前重置,包括測試依賴項,因此它不會像您預期的那樣工作。
但是你仍然可以做兩個測試並且讓一個依賴於另一個,但是你需要在兩個測試中重新運行相同的代碼(因為數據庫會在測試之間被重置)。 在這種情況下,“依賴”只是記錄一個測試與另一個測試相關聯。
public function testOne()
{
$this->expectException(Exception::class);
$this->expectExceptionMessage('xxxx');
app(Command::class)->handle();
}
/**
* @depends testOne
*/
public function testTwo($arg)
{
app(Command::class)->handle();
$this->seeInDatabase($table, [
'id' => $media->id(),
]);
}
如果您真的想對其進行端到端測試,並在同一個測試中進行斷言,那么您可以使用try... catch
塊並按程序進行測試。
public function testException()
{
try {
app(Command::class)->handle();
} catch (\Exception $e) {
// Make sure you catch the specific exception that you expect to be
// thrown, (e.g. the exception you would normally specify in the
// expectException method: $this->expectException(Exception::class);
// Assert the exception message.
$this->assertEquals('xxxx', $e->getMessage());
// Assert database still contains record.
$this->seeInDatabase($table, [
'id' => $media->id(),
]);
return;
}
// If the expected exception above was not caught then fail the test.
$this->fail('optional failure message');
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.