目前正在进行一个项目,该项目要求我为我实现的所有代码编写单元测试。我刚开始编写单元测试,最近我学到了使用@MockBeans、@InjectMocks、@Spy等注释编写测试用例的知识,以帮助我测试特定的方法。
然而,有时我确实为编写无法模拟的测试用例而挣扎,最终它变成了一个集成测试。下面是我在编写测试用例时遇到的一些场景。
服务层的
- The repo layer returns a list of Tuple (`javax.persistence.tuple`) back to the service layer.
- Mocked the repo layer, no issue on that.
- Tried creating the list of Tuple that was supposed to be returned when the repo layer is called through Mockito.when(), however, I could not create the list of tuple as it does not have any setter method.
- Ended up with a unit test that performing the actual query to the database to retrieve the values out which makes the unit test more like an integration test.
AutowireCapableBeanFactory自动写入spring上下文中。
- Since I could not mock a static factory, I just pass in the value into the factory and let it return the concrete class accordingly.
- The concrete class returned by the factory could not be mocked.
- The unit test would end up testing the concrete class as well.
new ConcreteClass()而不是@Autowired.来实例化一个新类
- I think this is similar to the 2nd scenario I mentioned above.
- @MockBeans will not work here since the concrete class is not created using @Autowired.
这就是我目前面临的场景,我花了很多时间试图找出编写测试用例的正确方法,或者更确切地说,我应该如何设计代码以避免所有这些问题?感谢您对这些场景的反馈和帮助,以改进我编写单元测试或代码设计的方式,使其更具可测试性!
发布于 2019-12-30 07:26:41
PowerMockito来模拟新对象的创建。.withAnyArguments().thenReturn(concreteObject);
https://stackoverflow.com/questions/59526716
复制相似问题