我試圖拋出一個新的自定義異常,並編寫測試以確保它實際上被拋出。我在以下位置應用程序\例外創造了一個新的異常\ AgreementsNotSignedException.phpPHPUnit未使用Laravel 5.2找到自定義異常
<?php
namespace App\Exceptions;
class AgreementsNotSignedException extends \Exception {}
和我訂單的「結賬」的方法是這樣的:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Exceptions\AgreementsNotSignedException as AgreementsNotSignedException;
class Order extends Model
{
public function checkout()
{
throw new AgreementsNotSignedException("User must agree to all agreements prior to checkout.");
}
}
我是失敗的外觀基本測試像這樣:
<?php
use App\Order;
use App\Exceptions\AgreementsNotSignedException;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class OrderTest extends TestCase {
/** @test * */
function it_does_not_allow_the_user_to_checkout_with_unsigned_contracts()
{
$exceptionClass = get_class(new App\Exceptions\AgreementsNotSignedException());
$this->setExpectedException(
$exceptionClass, 'User must agree to all agreements prior to checkout.'
);
try {
$this->order->checkout();
} catch (App\Exceptions\AgreementsNotSignedException $exception) {
$this->assertNotEquals($this->order->status, "completed");
}
}
}
消息吐爲「失敗斷言類型‘應用程序\例外\ AgreementsNotSignedException’的那則拋出異常。」。不過,我可以通過xdebug驗證異常是否被捕獲。傑夫在評論中指出,這似乎是一個FQN問題,因爲這樣做使得測試合格:
/** @test * */
function it_does_not_allow_the_user_to_checkout_with_unsigned_contracts()
{
$exceptionClass = get_class(new App\Exceptions\AgreementsNotSignedException());
$this->setExpectedException(
$exceptionClass, 'User must agree to all agreements prior to checkout.'
);
throw new App\Exceptions\AgreementsNotSignedException('User must agree to all agreements prior to checkout.');
}
我會繼續通過改變FQN閒逛,但任何指導,將是真棒。
您需要指定預期異常的完全限定名稱空間,如[本問題](http://stackoverflow.com/q/14572469/697370) –
如何在OrderTest中定義$ this-> order類? – Matteo
它是一個受保護的變量,它在安裝方法(未顯示)中被賦值。順序變量很好,我可以在調用checkout之前用調試器驗證它的狀態。 – Msencenb