Laravel + 嘲讽 InvalidCountException

Laravel + Mockery InvalidCountException

我正在尝试模拟 a class 以防止它不得不调用第 3 方 api。但是在设置模拟时,它似乎并不影响控制器的动作。我确实尝试通过手动创建 Request- 和 OEmbedController-类 的实例来替换 $this->postJson()create() 方法正在被调用,但我从 Mockery 收到一个错误,它不是。

我做错了什么?

错误:

Mockery\Exception\InvalidCountException : Method create() from Mockery_2_Embed_Embed should be called exactly 1 times but called 0 times.

测试:

class OEmbedTest extends TestCase
{
    public function tearDown()
    {
        Mockery::close();
    }

    /**
     * It can return an OEmbed object
     * @test
     */
    public function it_can_return_an_o_embed_object()
    {
        $url = 'https://www.youtube.com/watch?v=9hUIxyE2Ns8';

        Mockery::mock(Embed::class)
            ->shouldReceive('create')
            ->with($url)
            ->once();

        $response = $this->postJson(route('oembed', ['url' => $url]));
        $response->assertSuccessful();
    }
}

控制器:

public function __invoke(Request $request)
{
    $info = Embed::create($request->url);

    $providers = $info->getProviders();

    $oembed = $providers['oembed'];

    return response()
        ->json($oembed
            ->getBag()
            ->getAll());
}

你似乎在用错误的方式嘲笑 Embed class。如果您使用 Laravel 门面方法 shouldReceive() 而不是创建 class 本身的模拟,框架将为您将模拟放置在服务容器中:

Embed::shouldReceive('create')
    ->with($url)
    ->once();

而不是

Mockery::mock(Embed::class)
    ->shouldReceive('create')
    ->with($url)
    ->once();

另请注意,如果您的测试代码传递给 mock 的参数与您通过 with($url) 了解的 mock 不同,则该 mock 认为自己未被调用。但是无论如何调用一个未定义的方法你都会收到另一个错误。

我在测试中使用这个解决了这个问题:

protected function setUp()
{
    parent::setUp();

    app()->instance(Embed::class, new FakeEmbed);
}

然后这样解决

$embed = resolve(Embed::class);
$embed = $embed->create($url);