在junit中替换spring容器中的依赖,最标准且推荐的做法是使用 @mockbean 注解。该注解会自动创建模拟对象并将其注册到spring容器中,直接覆盖原有的真实bean定义,从而实现对特定依赖的隔离测试。

如何为Controller注入MockService并验证调用?
通过 @MockBean 可以拦截对 MyService 的请求,转而使用模拟行为。以下代码展示了如何在测试类中声明模拟Bean,配置其返回逻辑,并在执行控制器方法后验证交互次数。

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
public class MyControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private MyService myService;
@Test
public void testGetItem() throws Exception {
// 配置模拟行为:当调用 getItem(1) 时返回 "Mocked Item"
when(myService.getItem(1)).thenReturn("Mocked Item");
// 执行请求
mockMvc.perform(get("/items/1"))
.andExpect(status().isOk());
// 验证是否调用了 mock 而非真实 Bean
verify(myService, times(1)).getItem(1);
}
}
如何区分MockBean与Spring Boot TestContext缓存的关系?
@MockBean 不仅替换了Bean,还影响了测试上下文的生命周期。每次测试方法执行前,Spring会确保容器中存在该模拟实例。如果多个测试类共享相同的上下文,@MockBean 的行为会被保留,直到上下文刷新。这意味着如果在不同测试中需要重置模拟状态,必须手动清除或重新配置。

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
public class MyControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private MyService myService;
@Test
public void testGetItemWithDifferentReturn() throws Exception {
// 重新配置模拟行为
when(myService.getItem(1)).thenReturn("New Mocked Item");
mockMvc.perform(get("/items/1"))
.andExpect(status().isOk());
verify(myService).getItem(1);
}
}
当MockBean未找到对应Bean时会发生什么?
如果 @MockBean 指定的类在当前Spring上下文中不存在任何Bean定义,Spring将不会抛出异常,而是直接注册一个新的模拟Bean。这可能导致测试无法按预期工作,因为原本可能依赖其他自动配置的Bean。因此,在使用 @MockBean 时,应确保该类确实存在于被测试的应用程序中,或者显式地导入相关配置。

















