Laravel 集成测试:如何断言一个 URL 已被调用,但另一个 URL 没有

我想测试一个向某个 URL 发出请求的控制器(例如:http://example.com/api/say-hello),但它没有向另一个网址(例如:http://example.com/api/say-bye-bye).

I would like to test a controller that makes a request to an certain URL (EG: http://example.com/api/say-hello) but it does not make a request to another URL (EG: http://example.com/api/say-bye-bye).

我要测试的控制器功能如下:

The controller function I want to test looks like this:

public function callApis(Request $request)
{
    $data = $this->validate($request, [
        'say_bye_bye' => 'nullable|boolean',
    ]);

    Http::get('http://example.com/api/say-hello');

    if ($data['say_bye_bye']) {
        Http::get('http://example.com/api/say-bye-bye');
    }
}

在我的集成测试中,我想确保:

In my integration tests, I want to make sure that:

  • 如果参数 say_bye_byeTRUE 则 API 端点 /api/say-hello/api/say-bye-bye 必须调用.
  • 如果参数 say_bye_byeFALSE 则只需调用 API /api/say-hello 并且 API 端点 /api/say-bye-bye 不得调用.
  • If the parameter say_bye_bye is TRUE then both of the API endpoints /api/say-hello and /api/say-bye-bye must be called.
  • If the parameter say_bye_bye is FALSE then just the API /api/say-hello has to be called and the API endpoint /api/say-bye-bye must NOT be called.

到目前为止,我设法验证是否使用 Http::assertSentCount(int $count) 进行了一两次调用.
解决方案可以是获取我正在测试的控制器调用的 URL 序列,但似乎没有办法.

So far I managed to verify if one or two calls have been made using Http::assertSentCount(int $count).
The solution can be getting the sequence of URLs called by the controller I'm testing, but it seems like there is no way.

推荐答案

可以使用Http::spy()

You can use Http::spy()

    Http::spy()
        ->expects('get')
        ->with('http://example.com/api/say-hello')
        ->once();
    Http::spy()
        ->expects('get')
        ->with('http://example.com/api/say-bye-bye')
        ->never();

相关文章