gpt4 book ai didi

java - Mockito 对象为 null

转载 作者:行者123 更新时间:2023-11-30 07:04:23 24 4
gpt4 key购买 nike

我正在尝试使用 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() 时,我收到 Null 异常。 在模拟测试中,我还尝试使用 Mockito.doReturn(tempObj).when(obj.attr2).create() 代替 Mockito.when(obj.attr2.create()) .thenReturn(tempObj)

但这也没有帮助。

我是否错误地模拟了 tempObj 对象?

最佳答案

如果您使用 @Mock 注释,请务必将您的类标记为使用 MockitoJUnitRunner:

@RunWith(MockitoJUnitRunner.class)
public class Test {
@Mock
private Foo foo; // will be instantiated by the runner rather than left null in OP question

关于java - Mockito 对象为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40390397/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com