You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

@RunWith(SpringRunner.class)与MockitoJUnitRunner对比及Mock注解兼容疑问

Switching from MockitoJUnitRunner to SpringRunner in Spring Boot Tests: Advantages & Mockito Annotation Compatibility

Great question! Making this switch makes perfect sense when working with Spring Boot apps—let’s break down the key benefits and clarify how Mockito’s core annotations fit into the picture.

Key Advantages of SpringRunner.class

  • Full Spring Context Integration: Unlike MockitoJUnitRunner, which only handles Mockito’s mocking logic, SpringRunner (an alias for SpringJUnit4ClassRunner) loads your Spring application context. This lets you use Spring’s core features like @Autowired, @Value, or @ConfigurationProperties in tests, and mix real Spring beans with mocks when needed.
  • Support for Spring Boot Test Slices: Spring Boot offers specialized test annotations like @SpringBootTest, @WebMvcTest, @DataJpaTest, etc. These "slice" annotations load only a subset of your app context (e.g., just the web layer or JPA components) for faster, focused tests—and they require SpringRunner to work correctly.
  • Seamless Spring Ecosystem Integration: If your tests involve Spring-specific modules like Spring Security, Spring Data, or Spring Cloud, SpringRunner enables smooth integration with their testing utilities. For example, you can use @WithMockUser for security testing or @DataJpaTest to auto-configure an in-memory database for repository tests.
  • Flexibility for Mixed Testing: You can combine pure unit testing (with Mockito mocks) and integration testing (with real Spring beans) in the same test class—something MockitoJUnitRunner can’t do, since it doesn’t load the Spring context at all.

Can You Still Use @InjectMocks, @Mock, @Spy?

Absolutely—but there are two approaches to choose from based on your needs:

  • Native Mockito Annotations: You can still use @Mock, @Spy, and @InjectMocks with SpringRunner, but you’ll need to initialize Mockito’s annotations manually. Add a @Before method to call MockitoAnnotations.openMocks(this) to set up the mocks. This works well if you only need mocks in your test class and don’t need them registered in the Spring context.
  • Spring’s Mock Annotations (Recommended for Spring Apps): For better integration with the Spring context, use Spring Boot’s @MockBean and @SpyBean instead. These annotations automatically register the mock/spy in the Spring context, replacing the real bean if it exists. This is ideal when you need to mock a bean that’s used by other Spring components (e.g., mocking a repository injected into a service). Note that @InjectMocks isn’t needed here—Spring’s dependency injection will handle injecting mocked beans into your test subject automatically.

Example: Using @MockBean with SpringRunner

@RunWith(SpringRunner.class)
@WebMvcTest(YourController.class)
public class YourControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private YourService yourService; // Replaces the real YourService in the Spring context

    @Test
    public void testControllerEndpoint() throws Exception {
        when(yourService.getData()).thenReturn("Mocked Data");

        mockMvc.perform(get("/api/data"))
               .andExpect(status().isOk())
               .andExpect(content().string("Mocked Data"));
    }
}

内容的提问来源于stack exchange,提问作者user8710021

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:20:14