alwaysAStudent
alwaysAStudent

Reputation: 2274

Junit Mockito not mocking as expected

I am trying to write a unit testing by mocking some of the methods. I am however facing some issue, wherein I believe one of the objects is not getting mocked.

class A {

   Class_C c;

   Class A(String x) {
        c = new Class_C(x);
   }

   public boolean internalMethod(String internalInput) {

       // Some Logic
       // Calls Inet4Address.getByName(internalInput)
   }

   public boolean method_to_be_tested(String input) {
       boolean result_1 = internalMethod(input);
       boolean result_2 = c.someMethod(result_1);

   }
}

The unit test I have written is as below:

 @Test
 public void test_method_to_be_tested() {

     A testObj = new A("test_input");
     testObj.c = Mockito.mock(Class_C.class);
     A spyTestObj = Mockito.spy(testObj);

     Mockito.when(spyTestObj.internalMethod(Mockito.anyString())).thenReturn(true);
     Mockito.when(spyTestObj.c.someMethod(Mockito.anyBoolean())).thenReturn(true); 

     Mockito.when(spyTestObj.test_method_to_be_tested("test_input")).thenCallRealMethod();

     Assert.assertTrue(spyTestObj.test_method_to_be_tested("test_input"));
 }

The error I am getting indicates Inet4Address.getByName() is getting invoked. It should not be since I have mocked out the output of the method in which it is called.

Upvotes: 4

Views: 7751

Answers (1)

Mureinik
Mureinik

Reputation: 312219

Mockito.when will invoke the real method. To work around this, you can use Mockito.doReturn instead:

Mockito.doReturn(true).when(spyTestObj).internalMethod(Mockito.anyString());
Mockito.doReturn(true).when(spyTestObj.c).someMethod(Mockito.anyBoolean());

Note that there's usually no need to mock calling the real method on a spied object - that's the default behavior anyway.

Upvotes: 4

Related Questions