dongliao1949 2019-08-13 12:39
浏览 103
已采纳

Phpunit:在Functional测试中对类中的方法进行存根

I am performing functional tests with PHPUnit in a Symfony 4.3 project. All my test classes extend from TestCase.

I am having problems to stub the result of a method that makes a call to an external service. I don't want to check that this service works in my project functional tests, so I do the following:

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);
    }

Here I see how the code continues going throw the real method ignoring the sub.

So my question is, how can I stub a method that is inside the logic to test, but I cannot call it directly in the test class?

Also, the constructor of the endpoint receives the Repository as an injection:

protected $externalRepository;

public function __construct(ExternalRepository $externalRepository)
{
    $this->externalRepository = $externalRepository;
    $this->commandBus = $commandBus;
}
  • 写回答

1条回答 默认 最新

  • dongritan5654 2019-08-13 16:08
    关注

    At the moment the best solution I found to functional test the controller is:

    1. Mock the external repository class, and stub the put method.
    2. Create a Controller object and inject the stub
    3. Invoke the Controller with the test request
    4. Assert that the return of the controller matches what is expected

      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);
      }
      
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 【求职】怎么找到一个周围人素质都很高不会欺负他人,并且未来月薪能够达到一万以上(技术岗)的工作?希望可以收到写有具体,可靠,已经实践过了的路径的回答?
  • ¥15 Java+vue部署版本反编译
  • ¥100 对反编译和ai熟悉的开发者。
  • ¥15 带序列特征的多输出预测模型
  • ¥15 Python 如何安装 distutils模块
  • ¥15 关于#网络#的问题:网络是从楼上引一根网线下来,接了2台傻瓜交换机,也更换了ip还是不行
  • ¥15 资源泄露软件闪退怎么解决?
  • ¥15 CCF-CSP 2023 第三题 解压缩(50%)
  • ¥30 comfyui openpose报错
  • ¥20 Wpf Datarid单元格闪烁效果的实现