[toc]
Main 3 annotations + simple use
annotation
@MockBean
Used alone, SpringBoot will replace the native bean managed by SpringBoot with this annotated bean when testing. Generally, this annotation is sufficient for testing.@Mock
Indicates that this is a mock object. Use@InjectMocks
can be injected into the corresponding bean. (Generally and@InjectMocks
together)@InjectMocks
Indicates that this object will be injected into the mock object. The injected object is the object just@Mock
marked .
@Mock
and @InjectMocks
one for marking and one for injection. You need to add @RunWith(MockitoJUnitRunner.class)
annotations in front of the test class MockitoJUnitRunner.class
to ensure that the@Mock
initialization of and before the test is executed. It is said that this method does not need to start the entire SpringContext, but now the SpringBootTest test can also specify which classes to initialize @InjectMocks
, the test is also very convenient.
Note:
@MockBean
The default behavior of the modified object is to do nothing. So use when(xxx).thenReturn(responsexx) to make it clear what the Mock object method should return.
Example
@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());
}
}
refer to
Spring Boot - Unit Testing and Mocking with Mockito and JUnit