我有一个API,我通过功能测试来测试它,一切都很好。问题出在以下情况。
我有一个控制器,它通过一个服务来执行一个外部API调用。我想在测试过程中模拟该服务,但我不知道如何做到这一点。
所以这可能是我的代码(作为一个例子)。
// src/service/MyService.php
class MyService
{
public function __construct(HttpClientInterface $client) {
$this->client = $client
}
public function call()
{
$this->client->get('https://api.com');
}
}
// src/controller/MyController.php
class MyController
{
/**
* @Route("/call")
*/
public function call(MyService $myService)
{
$myService->call();
}
}
// tests/controller/MyControllerTest.php
class MyControllerTest extends WebTestCase
{
public function testCall()
{
$client = static::createClient();
$client->request('GET', '/call');
$this->assertEquals(200, $client->getResponse()->getStatusCode());
}
}
我如何在测试中模拟MyService服务?
在功能测试中,你不需要这样做。功能测试意味着你想检查 "应用场景 "的测试,你给了输入,你期望一些输出行为。
你在这里需要的是(如果你想使用mock)MyService类的单元测试,在这里你应该模拟注入的类。