Mockito当thenreturn返回null

时间:2014-05-07 13:42:55

标签: java mockito

我试图将几个类存根,但Mockito总是返回null

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 {}

这可能是什么原因?

2 个答案:

答案 0 :(得分:1)

请改为尝试:

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 {}

答案 1 :(得分:0)

这里

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

Mockito将为接口B创建模拟对象(B mockB = mock(B.class);)并且您已经模拟了mockA.getB()以返回模拟对象(当(mockA.getB())。thenReturn(mockB) ;)所以肯定boolean b = mockA.getB()== null;将是假的

以下是可以帮助您的代码

以下是代码,如果它可以帮助您导入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 {
}