Spring boot Mokito 关键点简单理解

[toc]
主要3个注解 + 简单使用spring

注解

  • @MockBean 单独使用, SpringBoot 在测试时, 会用这个注解的bean替换掉 SpringBoot 管理的原生bean. 通常测试时这一个注解足以.
  • @Mock 表示这是一个 mock 对象. 使用@InjectMocks 能够注入到对应bean.(通常和@InjectMocks一块儿使用)
  • @InjectMocks 表示这个对象会注入 mock 对象. 注入的就是刚才被 @Mock 标注的对象.

@Mock@InjectMocks 一个用来标记, 一个用来注入. 须要在测试类前面添加 @RunWith(MockitoJUnitRunner.class) 注解, MockitoJUnitRunner.class会保证在执行测试之前, @Mock@InjectMocks 的初始化工做. 听说这种方式不用启动整个 SpringContext, 可是如今 SpringBootTest 测试也是能够指定初始化哪些类, 测试也很方便.springboot

注意: @MockBean 修饰的对象默认行为是什么都不作. 因此要用 when(xxx).thenReturn(responsexx) 来明确 Mock 对象方法要返回什么.spring-boot

示例

@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测试

相关文章
相关标签/搜索