gpt4 book ai didi

java - 未 stub 调用的 native 类型的返回值

转载 作者:太空宇宙 更新时间:2023-11-04 06:30:40 25 4
gpt4 key购买 nike

我有一些 @Mock 对象,但没有指定在该对象上调用方法的返回值。该方法返回 int (不是 Integer)。我很惊讶地发现 Mockito 没有抛出 NPE 并返回 0。这是预期的行为吗?

例如:

class Foo {
public int getInt() {
return 1;
}
}
@Mock
private Foo foo;

@InjectMock
private ClassToTest classToTest;

@Test
public void doTest() {
int a = classToTest.callFoo(); // which calls foo.getInt()
Assert.AssertEquals(a, 0); // true

}

最佳答案

根据documentation :

By default, for all methods that return value, mock returns null, an empty collection or appropriate primitive/primitive wrapper value (e.g: 0, false, ... for int/Integer, boolean/Boolean, ...).

所以是的,这是预期的行为。您还可以使用以下内容覆盖默认 stub :

@Test
public void doTest() {
Mockito.when(foo.getInt()).thenReturn(15);
int a = classToTest.callFoo(); // which calls foo.getInt()
//Assert.assertEquals(a, 0); // NO LONGER TRUE
Assert.assertEquals(a, 15);

}

关于java - 未 stub 调用的 native 类型的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26148642/

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