Phpunit:在功能测试中在 class 中添加一个方法
Phpunit: Stubbing a method inside a class in a Functional test
我正在 Symfony 4.3 项目中使用 PHPUnit 执行功能测试。我所有的测试 class 都是从 TestCase 扩展而来的。
我在对调用外部服务的方法的结果进行存根时遇到问题。我不想在我的项目功能测试中检查此服务是否有效,因此我执行以下操作:
public function testPutEndpoint()
{
$stub = $this->createMock(ExternalRepository::class);
$stub->method('put')->willReturn(['data'=> ['data']]);
{
list($responseCode, $content) = $this->makeCurl(
//Here a curl to the endpoint of my project is done
);
$this->assertEquals(200, $responseCode);
}
在这里我看到代码如何继续抛出忽略子的真实方法。
所以我的问题是,我怎样才能将逻辑内部的方法存根以进行测试,但我不能在测试中直接调用它class?
此外,端点的构造函数接收存储库作为注入:
protected $externalRepository;
public function __construct(ExternalRepository $externalRepository)
{
$this->externalRepository = $externalRepository;
$this->commandBus = $commandBus;
}
目前我发现对控制器进行功能测试的最佳解决方案是:
- 模拟外部存储库 class,并存根 put 方法。
- 创建控制器对象并注入存根
- 用测试请求调用控制器
断言控制器的return符合预期
public function testPut()
{
$stub = $this->createMock(CatalogRepository::class);
$stub->method('put')->willReturn([0 => 200, 1 => ['data' => 12355]]);
$request = Request::create('/path', Request::METHOD_PUT, [], [], [], [], ['body']);
$putController = new PutController($stub);
$response = $putController->__invoke($request);
$expectedResponse = 'expected response'
$this->assertEquals($expectedResponse, $response);
}
我正在 Symfony 4.3 项目中使用 PHPUnit 执行功能测试。我所有的测试 class 都是从 TestCase 扩展而来的。
我在对调用外部服务的方法的结果进行存根时遇到问题。我不想在我的项目功能测试中检查此服务是否有效,因此我执行以下操作:
public function testPutEndpoint()
{
$stub = $this->createMock(ExternalRepository::class);
$stub->method('put')->willReturn(['data'=> ['data']]);
{
list($responseCode, $content) = $this->makeCurl(
//Here a curl to the endpoint of my project is done
);
$this->assertEquals(200, $responseCode);
}
在这里我看到代码如何继续抛出忽略子的真实方法。
所以我的问题是,我怎样才能将逻辑内部的方法存根以进行测试,但我不能在测试中直接调用它class?
此外,端点的构造函数接收存储库作为注入:
protected $externalRepository;
public function __construct(ExternalRepository $externalRepository)
{
$this->externalRepository = $externalRepository;
$this->commandBus = $commandBus;
}
目前我发现对控制器进行功能测试的最佳解决方案是:
- 模拟外部存储库 class,并存根 put 方法。
- 创建控制器对象并注入存根
- 用测试请求调用控制器
断言控制器的return符合预期
public function testPut() { $stub = $this->createMock(CatalogRepository::class); $stub->method('put')->willReturn([0 => 200, 1 => ['data' => 12355]]); $request = Request::create('/path', Request::METHOD_PUT, [], [], [], [], ['body']); $putController = new PutController($stub); $response = $putController->__invoke($request); $expectedResponse = 'expected response' $this->assertEquals($expectedResponse, $response); }