Mock依赖:
SpringBoot依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<artifactId>spring-test</artifactId>
<groupId>org.springframework</groupId>
</exclusion>
</exclusions>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.1.RELEASE</version>
<scope>test</scope>
</dependency>
SpringMvc依赖:
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.8.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
Mock对象
DemoDao demoDao = mock(DemoDao.class);
对象注入到bean
ReflectionTestUtils.setField(demoBean, "demoDao", demoDao);
mock的对象只对demoBean有效,其他地方用到了demoDao,需要重新注入(ReflectionTestUtils.setField(demoBean2, "demoDao", demoDao);)
MockBean
@Service
public class DemoServiceMock {
@MockBean
protected DemoService demoService;
/**
* mock调用方法
*/
public void mockPInstanceNull(String param) {
when(demoService.demoTest(ArgumentMatchers.eq(param))).thenReturn("demoTestString");
} }
注意:
1.DemoServiceMock 不能被继承,否则会报错
- @MockBean
protected DemoService demoService;
不能在其他地方声明,否则报错
3.尽量使用eq()方法,慎用any**()方法