【发布时间】:2015-11-04 12:35:40
【问题描述】:
我的申请写在spring boot。
我正在使用testNG 和mockito 进行单元测试。
我对单元测试的工作有点困惑。
以下是我的测试课
class StudentServiceTest {
@mock
StudentDAO studentDAO;
@InjectMocks
StudentService studentService;
@BeforeMethod
public void initMock() {
studentService = new StudentService();
MockitoAnnotations.initMocks(this);
}
@Test(dataprovider.....)
public void shouldxxxxx(int id......) {
when(studentDAO.findOne(id)).thenReturn(Student);
assert......
}
}
当我运行上面的测试时。它工作正常。
我有以下疑问。
- 是否涉及弹簧。如果不是,那么@mock 和其他代码是如何工作的
- 我们是否应该涉及 spring。如果不/是,为什么?
- 我使用了new关键字来初始化服务。好吗。 正如在spring unit test documentation 中他们所说的那样
您可以使用 new 运算符简单地实例化对象,甚至无需涉及 Spring。您还可以使用模拟对象而不是真正的依赖项
如果我不使用 new 关键字实例化服务,则会显示错误 “无法实例化 @InjectMocks”。
如果我 autowired 服务,那么它需要 spring 容器,而且我运行单个测试,运行时间太长。如果not autowired 并使用new 关键字,那么它运行得非常快。
- 上面的代码干净吗?请建议使用 testNg 和 mockito 在 Spring Boot 中编写单元测试的最佳实践。
【问题讨论】:
标签: spring unit-testing spring-boot testng mockito