gpt4 book ai didi

java - 如何使用 Mockito 模拟方法调用链

转载 作者:行者123 更新时间:2023-12-01 14:21:26 25 4
gpt4 key购买 nike

我有一个这样的功能:

    @Override
public ClassA createViewModel(ClassB product, ClassC classCVar)
throws ModuleException
{
ClassA classAVar = ClassA.builder().build();
try {
if (product != null && product.getProductData() != null) {

String gl_name = product.getProductData().offers().get(0).productCategory().asProductCategory()
.inlined().map(ProductCategory::glProductGroup).map(ProductCategory.GLProductGroup::symbol)
.orElse("");
classAVar.setName = gl_name;

}
return classAVar;
} catch (Exception e) {
// some lines of code.
}

我这里有一行像 String gl_name = ........
它包含一个方法调用链。
现在我想使用 Mockito 来模拟这个函数,并希望从所有这些函数调用中得到最终结果,就像 gl_name = "abc";

我怎样才能做到这一点?

我创建了一个新函数,并将方法调用链放入其中,如下所示:
public String fetchGLNameFunction(ClassB product)
{
String gl_name_result = product.getProductData().offers().get(0).productCategory().asProductCategory()
.inlined().map(ProductCategory::glProductGroup).map(ProductCategory.GLProductGroup::symbol)
.orElse("");
return gl_name_result;
}

现在我尝试创建一个这样的模拟:
@Mock
private ClassA classAVar;
..........
............

@Test
public void testfunction1() throws Exception
{
when(classAVar.fetchGLNameFromAmazonAPI(classBVar)).thenReturn("abc");

它仍然给我 NullPointerException 因为它正在执行我新创建的函数。

最佳答案

Mockito您需要定义模拟对象的行为。

    //  create mock
ClassB product = mock(ClassB.class);

// Define the other mocks from your chain:
// X, Y, Z, ...

// define return value for method getProductData()
when(product.getProductData()).thenReturn(X);
when(X.offers()).thenReturn(Y);
when(Y.get(0)()).thenReturn(Z); // And so on.... until the last mock object will return "abc"

关于java - 如何使用 Mockito 模拟方法调用链,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49839808/

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