0

For Testing, I am using MockMvc to make a POST request to a Controller and I would like to Mock a particular service call so that it does nothing (with the Mockito.doNothing()). If I call that method within the @Test, then it works perfectly and the method is not called. The problem occurs when I do a mockMvc.perform(..) and the execution hits the controller, the method doNothing() is ignored and the function is executed. I am running the Spring MVC tests in a WebApplicationContext.

This is the setup:

@Mock
private MyService myService;

@Before
public void setup() {
    MockitoAnnotations.initMocks(this);
}

This part works. When myFuncToIgnore() is called, it is skipped.

@Test
public void myTest() throws Exception {
    Mockito.doNothing().when(myService)
    .myFuncToIgnore(isA(String.class), isA(String.class));

    myService.myFuncToIgnore("", "");
}

This part doesn't work. When the mockMvc calls the controller the block is executed. Please note that the controller calls an interface, whose implementation calls MyService, which is an interface with an impl called MyServiceImpl). Here is the code:

mockMvc.perform(
            post(serviceContextPath)
                    .contentType(MediaType.APPLICATION_JSON)
                    .header("X-Request-Language", "en"))
            .andDo(print())
            .andExpect(status().isOk())
            .andReturn();

Do you have any suggestions please?

patri
  • 59
  • 9
  • How do you "inject" the mock into the tested controller? Can you post a [mcve]? –  Nov 08 '17 at 14:49
  • that is what I would like to know how. With standalone context it can be done using the following syntax: MockMvcBuilders.standaloneSetup(controllerUnderTest).build(), but for WebApplicationContext I cant find a working way to do it. The suggestions suggested here didnt work for me: https://stackoverflow.com/questions/31819375/inject-mock-into-spring-mockmvc-webapplicationcontext – patri Nov 08 '17 at 15:12
  • WIth WebApplicationContext you can use (in xml): ` com.foo.bar.MyService ` this declares a MyService that is a "mock" –  Nov 08 '17 at 15:40
  • is there a way to define it as a Bean annotation instead of in xml? I did the following: @Configuration static class Config { (At)Bean (At)Primary public ProxyFactoryBean myService() { return Mockito.mock(MyService.class); } } Is this correct though? The last part I couldn't translate it to Bean Annotation. – patri Nov 09 '17 at 08:49
  • yep should work with java config too, but I think it should be `@Bean("myService") private ProxyFactoryBean foo() { ProxyFactoryBean pfb = new ProxyFactoryBean(); pfb.setTarget(Mockito.mock(MyService.class)); pfb.setProxyInterfaces(new Class[]{MyService.class}); return pfb; }` to be equivalent –  Nov 09 '17 at 09:43
  • thanks it worked :) – patri Nov 09 '17 at 11:20

0 Answers0