如何告诉Mockito Mock注释返回一个非null的模拟对象?

时间:2015-10-05 07:18:37

标签: java unit-testing mockito

我正在尝试对一个方法进行单元测试,该方法具有不同的分支,具体取决于在其中创建的对象的值。以下代码演示了它。

public class AClass {

public void method2() {
  //Some code goes here
}
public void method1(BClass bObject) {
    C_Class cObject = bObject.someMethodThatReturnsC();
    if(cObject != null) {
        method2();
        method2();
    }
}}

以下是TestClass:

public class AClassTest {
@InjectMocks
AClass AClassSpy;

@Mock
BClass b_objectMock;

@Mock
C_Class c_objectMock;

@BeforeMethod
public void beforeMethod() {
  AClassSpy = spy(new AClass());      
  MockitoAnnotations.initMocks(this);
}

public void method1Test () {
    doReturn(c_objectMock).when(b_objectMock).someMethodThatReturnsC());
    AClassSpy.method1(b_objectMock);
    verify(AClassSpy, times(2).method2();
}
}

但是,它始终为FAILS,因为c_objectMock始终为null。我该怎么做才能告诉Mockito不要返回空对象?

2 个答案:

答案 0 :(得分:2)

效果很好,只需使用junit中的@Before注释,而不是@BeforeMethod,并将测试方法标记为@Test并从第二个方括号中移除 doReturn(c_objectMock).when(b_objectMock).someMethodThatReturnsC())<-this one;
并在验证时添加括号:
verify(AClassSpy, times(2)<-here.method2();
并且只需照顾好您的代码!

这应该有效:

public class AClassTest {

  @InjectMocks
  private AClass AClassSpy;

  @Mock
  private BClass b_objectMock;

  @Mock
  private C_Class c_objectMock;

  @Before
  public void beforeMethod() {
      AClassSpy = spy(new AClass());
      MockitoAnnotations.initMocks(this);
  }

  @Test
  public void method1Test() {
      doReturn(c_objectMock).when(b_objectMock).someMethodThatReturnsC();
      AClassSpy.method1(b_objectMock);
      verify(AClassSpy, times(2)).method2();
  }

}

您可以使用注释@RunWith代替之前的方法。看起来很清楚:

@RunWith(MockitoJUnitRunner.class)
public class AClassTest {

  @Spy
  @InjectMocks
  private AClass AClassSpy;

  @Mock
  private BClass b_objectMock;

  @Mock
  private C_Class c_objectMock;

  @Test
  public void method1Test() {
      doReturn(c_objectMock).when(b_objectMock).someMethodThatReturnsC();
      AClassSpy.method1(b_objectMock);
      verify(AClassSpy, times(2)).method2();
  }

}

答案 1 :(得分:1)

您遇到此行为是因为您没有嘲笑对someMethodThatReturnsC的调用属性。

It should be

doReturn(c_objectMock).when(b_objectMock).someMethodThatReturnsC();