使用PhpUnit模拟捕获异常

使用PhpUnit模拟捕获异常,phpunit,Phpunit,最近我看到一些关于我的项目的问题,发现有一些例外,我忘记捕捉它们!这是我的代码: try { $this->user = $invoiceEvent->user; $this->invoice = $invoiceEvent->invoice; if ($this->user->email) { $this->sendEmail(); } }catch (Swift_RfcComplianceExcep

最近我看到一些关于我的项目的问题,发现有一些例外,我忘记捕捉它们!这是我的代码:

try {
    $this->user = $invoiceEvent->user;

    $this->invoice = $invoiceEvent->invoice;

    if ($this->user->email) {
        $this->sendEmail();
    }
}catch (Swift_RfcComplianceException $e) {

}
通过使用这个try/catch,我的问题解决了,这是我的测试,是绿色的!,谁可以断言异常为catch

 /**
 * @test
 */
public function it_should_Not_provide_exception_when_mailFromAddress_is_not_set()
{

    $invoice = $this->makeInvoice();
    $user = $this->makeUser();
    $mail = app('Illuminate\Contracts\Mail\Mailer');

    (new SendInvoiceToUser($mail))->handle(new InvoiceCreated($invoice, $user)); 

}

最后,使用这种方式,我断言异常catch,在这种情况下,我的方法返回null,这正是我所期望的

/**
 * @test
 */
public function it_should_Not_provide_exception_when_mailFromAddress_is_not_set()
{

    $invoice = $this->makeInvoice();
    $user = $this->makeUser();
    $mail = app('Illuminate\Contracts\Mail\Mailer');


    $mocked = $this->getMockBuilder(SendInvoiceToUser::class)
        ->setConstructorArgs([$mail])
        ->setMethods(null)
        ->getMock();

    $this->assertNull($mocked->handle(new InvoiceCreated($invoice, $user)));
}
  • 通过将null传递到->setMethods(null),mock对象在调用时运行方法中包含的实际代码