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

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即可.





评论 4
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值