Mockito启动相关

一般情况下,如果要使Mockito注解(@Mock, @Spy, @InjectMocks等)生效,也就是初始化那些用Mockito注释修饰的字段,则需要在测试类上面加上@RunWith(MockitoJUnitRunner.class)注解,然后搭配@SpringBootTest使用。

@RunWith(MockitoJUnitRunner.class)
@SpringBootTest(class = xxxx.class)
public class Test {
     ...
}

关联知识补充:

  • @SpringBootTest()
    • 加载ApplicationContext,启动Spring容器。
    • 加载@SpringBootApplication、@SpringBootConfiguration的配置
  • @RunWith()
    • 运行Spring容器时,将括号中的内容与容器进行关联

另一种初始化字段的方式是在Junit @Before修饰的方法中调用MockitoAnnotations.openMocks(Object)。

public class Test {

    private AutoCloseable closeable;

    @Before 
    public void before() {
        closeable = MockitoAnnotations.openMocks(this);
    }

    @After 
    public void after() throws Exception {
        closeable.close();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值