dongpai6552 2016-03-30 12:43
浏览 46
已采纳

模拟测试的服务或测试实例

I ended up in a discussion with one of our my colleagues about how to setup a unit-test for testing a service class.

When setting up the test case one of us suggests mocking the actual class that we are testing, while the other prefers to make an instance of the class and only mocking the dependencies.

So let's say we are testing SomeService

One solution would be to mock the actual service and test the mock:

$firstDependency  = //create mock for first dependency
$secondDependency = //create mock for second dependency
$this->someService = $this->getMockBuilder(SomeService::class)
     ->setMethods(null)
     ->setConstructorArgs(array($firstDependency, $secondDependency))
     ->getMock();

// continue testing $this->someService which is a mock

The other solution would be to test the instance of the service and only mocking the dependencies:

$firstDependency  = //create mock for first dependency
$secondDependency = //create mock for second dependency
$this->someService= new SomeService($firstDependency, $secondDependency);

// continue testing $this->someService which is direct instance of SomeService

Which of these solutions is considered best practice?

Answers preferably with some reference to official php-unit documentation or other reliable sources.

  • 写回答

3条回答 默认 最新

  • dousha1873 2016-03-30 13:24
    关注

    Don't mock class under test. Not exactly php-unit documentation, yet all the points are still valid. Mocking the SUT you end up testing the mock, not the actual class that will be used in production.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器