我正在尝试抛出一个新的自定义异常,并编写测试以确保它实际被抛出。我在以下位置创建了一个新的异常App \ Exceptions \ AgreementsNotSignedException.php
<?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");
}
}
}
消息spit out''失败断言类型异常“App \ Exceptions \ AgreementsNotSignedException”被抛出。'。但是,我可以通过xdebug验证异常确实被捕获。正如Jeff在评论中所说的那样,它似乎是一个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 :(得分: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)
代替了它。
答案 1 :(得分: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.'
);