Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito mocking a method calls the actual method

I am trying to mock method createInstanceB() using Mockito.when() as well as doReturn(). This always calls real method.

For example:

Class A {
  public B createInstanceB(any, any) {
    B b = new B();
    b.api();
  }
}

I am using the code below

import org.mockito.Mockito;
import static org.mockito.Mockito.*;

    Class ATest {
      A a;
      B b;

      @Before
      Public void setup{
        a = A.getInstance();
        b = mock(B.class);
      }
  
      @Test
      public void testCreateInstanceB(){
        Mockito.when(a.createInstanceB(any(),any()).thenReturn(b);
        ...
      }
    }

I tried doReturn(mock) as well.

like image 499
user3754993 Avatar asked Jan 03 '23 17:01

user3754993


1 Answers

As StvnBrkdll recommended, use a Spy if you're needing to use an actual instance. But that can still call the real method sometimes if using Mockito.when() as you are in your example. As an alternative, look at Mockito.doReturn(). For example using your code: Mockito.doReturn(b).when(a).createInstanceB(any(),any()); This will now only return b and never call the actual method of createInstanceB.

Btw, their docs have a section about this. See the part under "Important gotcha on spying real objects!"

like image 60
AndyB Avatar answered Jan 12 '23 06:01

AndyB