首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >编写可测试代码. Junit测试

编写可测试代码. Junit测试
EN

Stack Overflow用户
提问于 2019-12-30 06:39:07
回答 1查看 455关注 0票数 0

目前正在进行一个项目,该项目要求我为我实现的所有代码编写单元测试。我刚开始编写单元测试,最近我学到了使用@MockBeans@InjectMocks@Spy等注释编写测试用例的知识,以帮助我测试特定的方法。

然而,有时我确实为编写无法模拟的测试用例而挣扎,最终它变成了一个集成测试。下面是我在编写测试用例时遇到的一些场景。

服务层的

  1. 单元测试最终成为一个集成测试,因为它与回购层交互。

代码语言:javascript
复制
- 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.

  1. 是一种包含工厂方法调用的方法。工厂类作为静态类编写,返回的具体类随后使用AutowireCapableBeanFactory

自动写入spring上下文中。

代码语言:javascript
复制
- 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.

  1. 实例化一个新类的方法,它使用new ConcreteClass()而不是@Autowired.

来实例化一个新类

代码语言:javascript
复制
- 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.

这就是我目前面临的场景,我花了很多时间试图找出编写测试用例的正确方法,或者更确切地说,我应该如何设计代码以避免所有这些问题?感谢您对这些场景的反馈和帮助,以改进我编写单元测试或代码设计的方式,使其更具可测试性!

EN

回答 1

Stack Overflow用户

发布于 2019-12-30 07:26:41

  1. 您可以使用PowerMockito来模拟新对象的创建。

.withAnyArguments().thenReturn(concreteObject);

  • Reflection可以用来模拟工厂类。
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59526716

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档