douxiong3234 2017-08-03 21:59
浏览 75

自动注入单元测试的依赖项

Coming from Java background, I am working on php codebase and want to add unit tests for my code.

I have a service class which has a DAO class as below :

class ServiceClass {

  private $daoClass;

  public function methodToTest(){}
}

I don't provide a constructor nor do I add a setter method for the daoClass property. This is because it will get injected using PHP-DI IoC container.

For unit testing, I am using phpunit, so I am mocking the daoClass object and using reflection to inject that property directly (as there is no constructor or setter for that property).

In java, we can easily do this without the reflection stuff using @InjectMocks annotation or MockitoAnnotations.initMocks method.

I am not able to find a similar way to do this in phpunit.

Also, a different but related question, is there any way in my test I can create a private property and annotate it with some tag, and it automatically gets converted to a mock object instance? Like how mockito in Java does it @Mock annotation.

  • 写回答

1条回答 默认 最新

  • dougui2254 2017-08-08 19:41
    关注

    I don't know myself of any mock-by-annotation (see the first comment for a link of such), but for your testing purposes you could create your own mock for such service classes in plain PHP that you use in testing. This is rather straight forward and only requires that autoloading is properly configured for development. This has the benefit that your library ships with suitable mocks which otherwise you would intermix into production code with annotations that are designed for tests only but spread into non-test context.

    This might not be exactly what you're looking for when coming from Java, but I have made good experiences in PHP with such "hand-written" test-helpers especially when it comes to some family of classes. In the end they are pretty useful and can safe a lot of repetition in tests. Sometimes they are even necessary as dynamically created mocks can't express and assert what might be required in testing.

    评论

报告相同问题?

悬赏问题

  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因