您的位置:首页 > 编程语言 > Java开发

spring-boot整合Mock进行单元测试

2016-09-13 09:18 447 查看
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即可.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息