Question

I am trying to stub few classes but Mockito returns null always

class test {
  A mockA = mock(A.class);
  B mockB = mock(B.class);

  when(mockA.getB()).thenReturn(mockB);
  boolean b = mockA.getB() == null //true
}

interface A {
 B getB();
}

interface B {}

What could be the reason of that?

Was it helpful?

Solution

Try this instead:

class test {
    A mockA = mock(A.class);
    B mockB = mock(B.class);

    when(mockA.getB()).thenReturn(mockB);
    boolean b = mockA.getB() == null; // Should be false
}

interface A {
    B getB();
}

interface B {}

OTHER TIPS

Here

class test {
A mockA = mock(A.class);
B mockB = mock(B.class);
when(mockA.getB()).thenReturn(mockB);
boolean b = mockA.getB() == null;
}

Mockito will create mocked object for interface B (B mockB = mock(B.class);) and you have mocked mockA.getB() to return mocked object (when(mockA.getB()).thenReturn(mockB);) so surely boolean b = mockA.getB() == null; will be false

Here is code it may help you

Here is code if it may help you import org.mockito.Mockito;

public class Test {

public static void main(String dd[]) {
    A mockA = Mockito.mock(A.class);
    B mockB = Mockito.mock(B.class);

    Mockito.when(mockA.getB()).thenReturn(mockB);
    boolean b = mockA.getB() == null; // true
    System.out.println(b);
}
}

interface A {
B getB();
}
interface B {
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top