为什么laravel断言不是从闭包中调用的?

时间:2016-05-16 07:56:42

标签: laravel laravel-5.2

我的代码是:

public function testOne()
{
    $mail = ['subject' => 'My subject'];

    $this->assertEquals(1, 1);
    $mock = Mockery::mock(\Illuminate\Support\Facades\Mail::getSwiftMailer());
    $this->app['mailer']->setSwiftMailer($mock);
    $msg = $mock->shouldReceive('send')->once()->andReturnUsing(function($msg) {
        echo $msg->getSubject();
        $this->assertEquals($mail['subject'], $msg->getSubject());
    });
    $this->assertEquals(1, 1);
}

我得到输出:

PHPUnit 4.8.24 by Sebastian Bergmann and contributors.

My subject

Time: 852 ms, Memory: 26.00Mb

OK (1 test, 2 assertions)

我从输出中看到:

echo $msg->getSubject();

我得到了很好的主题,但没有任何断言,为什么?

1 个答案:

答案 0 :(得分:0)

像这样使用

public function testOne()
{
    $mail = ['subject' => 'My subject'];

    $this->assertEquals(1, 1);
    $mock = Mockery::mock(\Illuminate\Support\Facades\Mail::getSwiftMailer());
    $this->app['mailer']->setSwiftMailer($mock);
    $obj = $this;
    $msg = $mock->shouldReceive('send')->once()->andReturnUsing(function($msg) use ($obj, $mail) {
        echo $msg->getSubject();
        $obj->assertEquals($mail['subject'], $msg->getSubject());
    });
    $this->assertEquals(1, 1);
}

closure的{​​{1}}个实例中,所以它不会从那里获得Closure因为你必须分配给另一个变量&用它。

  

<强> $this

But you can rewrite your tests like this