Search code examples
javaunit-testingmockitospy

How to use mockito to not evaluate a method inside the testing method



I am implementing a test case for a controller method. The controller method looks like below,

public class LoginController{
   public String register(String token){
     //some logic 
     loginService.delete(String token);
    //some logic
   return "xxxx";
   }
}

I am implementing the test case to test the register method and i do not want the method delete to be evaluated. (The delete method is a service method that returns a void). I did a bit of research and used the below code in my test method to not evaluate the delete method, but still when i debug it goes inside the delete method. Can anyone point put me out what wrong I have done.

public class LoginControllerTest{
   private loginService loginServiceMock;

   @Test
   public void testRegister(){
      loginServiceMock = new loginServiceImpl();
      loginService spy = spy(loginServiceMock);
      doNothing().when(spy).delete(any(String.class));
      //calling the controller method 
   }
}

Solution

  • What you are doing should work as long as loginService spy object is injected into LoginController that you are testing. This is not visible from the code you've posted.

    There are 2 reasons that would make the controller call the real login service method :

    1. You forgot to inject the spy into the controller: something like loginControllerToTest = new LoginController(spy) or loginControllerToTest.setLoginService(spy).

    2. loginService.delete() is a static method in which case you need to either refactor your code to remove static dependency or use a different mocking tool such as powermock. See this question for details.