一般情况下,如果要使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();
}
}