@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 forSpringJUnit4ClassRunner) loads your Spring application context. This lets you use Spring’s core features like@Autowired,@Value, or@ConfigurationPropertiesin 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 requireSpringRunnerto work correctly. - Seamless Spring Ecosystem Integration: If your tests involve Spring-specific modules like Spring Security, Spring Data, or Spring Cloud,
SpringRunnerenables smooth integration with their testing utilities. For example, you can use@WithMockUserfor security testing or@DataJpaTestto 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
MockitoJUnitRunnercan’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@InjectMockswithSpringRunner, but you’ll need to initialize Mockito’s annotations manually. Add a@Beforemethod to callMockitoAnnotations.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
@MockBeanand@SpyBeaninstead. 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@InjectMocksisn’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
相关产品推荐
相关产品推荐

