[toc]
主要3个注解 + 简单使用
注解
@MockBean
单独使用, SpringBoot 在测试时, 会用这个注解的bean替换掉 SpringBoot 管理的原生bean. 一般测试时这一个注解足以.@Mock
表示这是一个 mock 对象. 使用@InjectMocks
可以注入到对应bean.(一般和@InjectMocks
一起使用)@InjectMocks
表示这个对象会被注入 mock 对象. 注入的就是刚才被@Mock
标注的对象.
@Mock
和 @InjectMocks
一个用来标记, 一个用来注入. 需要在测试类前面添加 @RunWith(MockitoJUnitRunner.class)
注解, MockitoJUnitRunner.class
会保证在执行测试以前, @Mock
和 @InjectMocks
的初始化工作. 据说这种方式不用启动整个 SpringContext, 但是现在 SpringBootTest 测试也是可以指定初始化哪些类, 测试也很方便.
注意:
@MockBean
修饰的对象默认行为是什么都不做. 所以要用 when(xxx).thenReturn(responsexx) 来明确 Mock 对象方法要返回什么.
示例
@MockBean
@RunWith(SpringRunner.class)
@SpringBootTest(classes = { Xxx.class, X.class}) // 普通Spring方式测试
public class Test{
@MockBean
private DataService dataService; // 定义Mock类, 在test环境下, 会被Spring管理
@Autowired
private Xxx xxx;
@Test
public void test() throws Exception {
Response mockResponse = structMockResponse();
when(dataService.findByCondition(Matchers.any(Condition.class), Matchers.anyMap()))
.thenReturn(mockResponse); // 定义Mock类行为
xxx.service(); // 并没有直接调用 dataService 相关联的类. @MockBean 在测试环境下, 替换掉 Spring 管理的类. `@Autowired` 注入类型和 `@MockBean` 标记类相同时, 会注入Mock 类.
// Assert ignored ..
}
public void structMockResponse(){
// ...
return null;
}
}
@Mock & @InjectMocks
@RunWith(MockitoJUnitRunner.class) // 需要使用MockitoJUnitRunner启动测试
public class BusinessServicesMockTest {
@Mock
DataService dataServiceMock; // 标示Mock类
@InjectMocks
BusinessService businessImpl; // 注入Mock类
@Test
public void testFindTheGreatestFromAllData() {
when(dataServiceMock.retrieveAllData()).thenReturn(new int[] { 24, 15, 3 }); // 定义Mock类行为
assertEquals(24, businessImpl.findTheGreatestFromAllData());
}
@Test
public void testFindTheGreatestFromAllData_ForOneValue() {
when(dataServiceMock.retrieveAllData()).thenReturn(new int[] { 15 });
assertEquals(15, businessImpl.findTheGreatestFromAllData());
}
@Test
public void testFindTheGreatestFromAllData_NoValues() {
when(dataServiceMock.retrieveAllData()).thenReturn(new int[] {});
assertEquals(Integer.MIN_VALUE, businessImpl.findTheGreatestFromAllData());
}
}
参考
Spring Boot - Unit Testing and Mocking with Mockito and JUnit