【问题标题】:Phpunit: Stubbing a method inside a class in a Functional testPhpunit:在功能测试中对类内的方法进行存根
【发布时间】:2019-12-20 00:28:23
【问题描述】:

我在 Symfony 4.3 项目中使用 PHPUnit 执行功能测试。我所有的测试类都从 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);
    }

在这里我看到代码如何继续抛出忽略子的真实方法。

所以我的问题是,我怎样才能存根一个在逻辑内部进行测试的方法,但我不能直接在测试类中调用它?

另外,端点的构造函数接收 Repository 作为注入:

protected $externalRepository;

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

【问题讨论】:

    标签: php testing mocking phpunit stub


    【解决方案1】:

    目前我发现对控制器进行功能测试的最佳解决方案是:

    1. 模拟外部存储库类,并存根 put 方法。
    2. 创建一个控制器对象并注入存根
    3. 使用测试请求调用控制器
    4. 断言控制器的返回符合预期

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-26
      • 2020-02-11
      • 2015-08-23
      • 1970-01-01
      • 2013-07-08
      • 2014-08-02
      • 2019-04-15
      相关资源
      最近更新 更多