1.引包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
2.上代码
BeanTest.java
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = TestApplication.class) //使用TestApplication作为spring容器加载类
@ActiveProfiles("test") //这边test指配置文件指向spring-test.yml
@Rollback(false) //单元测试配置数据库默认会事务会退 此时强制事务提交
public class BeanTest {
@Mock
protected IdentityFactory factory;
@InjectMocks
@Autowired
private IdGenerator idGenerator;
@Before
public void mockIdentityFactory() {
Mockito.when(factory.next(Mockito.anyString())).thenAnswer(new Answer<Long>() {
@Override
public Long answer(InvocationOnMock invocationOnMock) throws Throwable {
Random random = new Random();
return (long) random.nextInt(1000);
}
});
}
@Test
public void test(){
idGenerator.getId();
}
}
@SpringBootApplication
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
上面这个例子IdGenerator就注入了IdentityFactory的实例,当执行到方法到actory.next会产生一个随机值
注意:
Mock在运行时匹配注入的一个条件是class匹配(class相同或者是其子类)
当Mock的类是一个接口;在spring ioc加载bean 对于接口默认产生动态代理的方式,此时会导致条件匹配失败;此时更改默认使用cglib方式加载bean即可.
3万+





