【发布时间】:2016-11-02 21:49:34
【问题描述】:
我正在尝试使用 Mockito 编写单元测试用例。下面是我的示例代码:
class A {
Attr1 attr1;
Attr2 attr2;
public boolean methodToBeTested(String str) {
Boolean status1 = attr1.doSomething();
TempObject temp = attr2.create();
Boolean result = anotherMethod() && temp.doAnotherThing();
}
boolean anotherMethod() {
return true;
}
}
我的测试班:
class ATest extends AbstractTestCase {
@Mock
Attr1 attr1;
@Mock
Attr2 attr2;
@Mock
TempObject tempObj;
A obj; // This is not mocked
@Before
public void setup() {
obj = new A(attr1, attr2);
}
@Test
public void testMethodToBeTested() {
Mockito.when(obj.attr1.doSomething()).thenReturn(true);
Mockito.when(obj.attr2.create()).thenReturn(tempObj);
Mockito.when(tempObj.doAnotherThing()).thenReturn(true);
Assert.assertTrue(obj.methodToBeTested(someString))
}
}
但是,当它尝试执行 temp.doAnotherThing() 时,我得到空异常。
在模拟测试中,我还尝试使用 Mockito.doReturn(tempObj).when(obj.attr2).create() 代替 Mockito.when(obj.attr2.create()).thenReturn(tempObj)
但这也无济于事。
我是否错误地模拟了对象 tempObj?
【问题讨论】:
-
你的意思是
tempObj? -
是的。我在测试类中将模拟对象命名为 tempObj,在实际类中命名为 temp。
标签: java unit-testing mocking mockito