Mockito test for service call on Legacy code

237 Views Asked by At

I am creating junit test case for legacy spring controller code which calls service (creates new instance of service call instead of autowire/spring bean). I want the service class call to be mocked. Please let know if it's possible.
Changing the legacy code is not an option for me.

public class WebController {

@PostMapping("/api/op1")
   public @ResponseBody String validate(ModelMap model,HttpSession session,HttpServletRequest request){
        ---
        --
        Service service = new Service();
        service.invoke(param1,param2);
        ----
        ---
   }
}

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
public class WebControllerTest{
    private MockMvc mockMvc;
    private WebController classUnderTest;

    @Test
    public void validat() throws Exception {
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();     

        //Service service = spy(Service.class);
        //doReturn(new ServiceCallResponse()).when(service).validate( any(String.class),any(String.class));

        Service service = Mockito.mock( Service.class, CALLS_REAL_METHODS );
        doReturn(new ServiceCallResponse()).when(service).validate(any(String.class),any(String.class));


        MvcResult result = mockMvc.perform(
                post("/validate").params(params).session(new MockHttpSession()))                            
                .andExpect(status().isOk())
                .andReturn();

    }

}

Spy and Mocktio calls real method options are not working. Please let know how to mock it.

0

There are 0 best solutions below