2016-05-25 72 views
1

我試圖拋出一個新的自定義異常,並編寫測試以確保它實際上被拋出。我在以下位置應用程序\例外創造了一個新的異常\ 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閒逛,但任何指導,將是真棒。

+0

您需要指定預期異常的完全限定名稱空間,如[本問題](http://stackoverflow.com/q/14572469/697370) –

+0

如何在OrderTest中定義$ this-> order類? – Matteo

+0

它是一個受保護的變量,它在安裝方法(未顯示)中被賦值。順序變量很好,我可以在調用checkout之前用調試器驗證它的狀態。 – Msencenb

回答

0

嘗試:

$this->setExpectedException(
      'App\Exceptions\AgreementsNotSignedException, 'User must agree to all agreements prior to checkout.' 
     ); 

,而不是這樣的:

$exceptionClass = get_class(new App\Exceptions\AgreementsNotSignedException()); 
     $this->setExpectedException(
      $exceptionClass, 'User must agree to all agreements prior to checkout.' 
     ); 
+0

不幸的是同樣的錯誤。我首先嚐試了這一點,並放棄了get_class方法,希望能更好地理解事物。儘管我已經設法使用assertThat和PHPUnit_Framework_Constraint_Exception來測試這個測試。 – Msencenb

1

剛剛有同樣的問題,並找到解決方案,基於源代碼,PHPUnit的$this->setExpectedException()方法已經過時了。

* * @since Method available since Release 3.2.0 * @deprecated Method deprecated since Release 5.2.0 */ public function setExpectedException($exception, $message = '', $code = null) {

我用$this->expectException(MyCustomException::class),而不是和它的工作。