79603432

Date: 2025-05-02 13:02:05
Score: 2.5
Natty:
Report link

Face the same issue today and this is my way to solve.

Root cause is the same: @MockitoSpyBean requires that you have a bean present that Mockito would be able to spy on. Previously, with @SpyBean bean was created if none was present.

I tested @ContextConfigure but it seems break the default auto configure which cause some of the filters/handlers are not loaded.

In this way, I use @Import at class level, and @MockitoSpyBean work as expected after.

@WebMvcTest(MyController.class)
@AutoConfigureMockMvc
@Import(MyBeanClass.class) // add this 
class MyControllerTest {

    @Autowired
    MockMvc mockMvc;

    @MockitoSpyBean
    MyBeanClass myBean;

    @Test
    void myTest() {
        
        mockMvc.perform(get('xxx'));
        // use Spy here. 
        verify(myBean, times(1)).xxx();
        
    }
}
Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Me too answer (2.5): Face the same issue
  • Low reputation (1):
Posted by: ChangHai Jiang