gpt4 book ai didi

unit-testing - Mockito.thenReturn(...) 不工作

转载 作者:行者123 更新时间:2023-11-28 21:26:43 24 4
gpt4 key购买 nike

测试类

public class CollectionImplementationUnitTest {

CollectionImplementation colImp;

public void setup() throws Exception {
...
colImp = Mockito.spy(new CollectionImplementation());
...
}

private String mockHistoryFromStrgyTable() {
String value1 = "myValue";
return value1;
}

@Test
public void testgetinfo (){
...
Mockito.when(
colImp.historyFromStrgyTable(
Mockito.anyString(),Mockito.anyString(),Mockito.anyString()
)
)
.thenReturn(mockHistoryFromStrgyTable());

CollectionsAccount Info = colImp.accountInfo(
"string1","string2","string3", new IdentityAcc(), TableLst
);

//sometestmethods and asserts
}
}

被测类

public class CollectionImplementation {
...
@Override
public CollectionsAccount accountInfo(("string1","string2","string3", new IdentityAcc(), TableLst)) {
DetailsHelper helper = new (db2, "string",getmethod());
return helper.accountInfo("string1","string2", new IdentityAcc(), TableLst);
}

public String historyFromStrgyTable(){
//contains a call to the data base
}
}

DetailsHelper

public class DetailsHelper{
public CollectionsAccount accountInfo((String string1,String string2,String string3, new IdentityAcc(), TableLst)){
...
String paymentdetails = historyFromStrgyTable();
}
public String historyFromStrgyTable(){
//contains a call to the data base
}
}

当我尝试模拟 HistoryFromStrgyTable() 方法的数据时,它实际上是在调用 HistoryFromStrgyTable() 而不是从 mockHistoryFromStrgyTable() 获取数据。

我的测试用例在这一行失败了

Mockito.when(col_Imp.HistoryFromStrgyTable(Mockito.anyString(),
Mockito.anyString(),Mockito.anyString())).thenReturn( mockHistoryFromStrgyTable());

谁能帮我解决这个问题。我不明白怎么了。我还将 mockHistoryFromStrgyTable() 方法从私有(private)更改为公共(public),因为 mockito 无法模拟私有(private)方法。

最佳答案

发生这种情况是因为您使用的是 spy ,而不是模拟。当您调用它时运行“真正的”方法正是 Mockito spy 应该做的。

要 stub 您的 spy ,这是您要使用的语法。

Mockito.doReturn(mockHistoryFromStrgyTable()).when(colImp).
historyFromStrgyTable(Mockito.anyString(),Mockito.anyString(),Mockito.anyString());

您可以在 my post here 中找到更多详细信息.

关于unit-testing - Mockito.thenReturn(...) 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38677048/

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