【发布时间】:2021-07-23 15:39:35
【问题描述】:
有一个类并想模拟/存根一个方法
public class ToBeMocked {
public List<HttpCookie> mergeList(@NonNull List<HttpCookie> cookies, HttpCookie oneCookie) {
System.out.println("+++ mergeList(), cookies:"+cookies+", oneCookie:"+oneCookie);
HashMap<String, HttpCookie> map = new HashMap();
if (oneCookie != null) {
map.put("A", oneCookie);
}
for (HttpCookie cookie : cookies) { //<=== it crashed at this line
map.put(cookie.getName(), cookie);
}
List<HttpCookie> list = new ArrayList<HttpCookie>();
for (Map.Entry<String, HttpCookie> entry : map.entrySet()) {
list.add(entry.getValue());
}
return list;
}
}
测试;
@Test
public void test() {
List<HttpCookie> aCookieList = new ArrayList<>();
HttpCookie a1Cookie = new HttpCookie("A1", "a1");
HttpCookie a2Cookie = new HttpCookie("A2", "a2");
aCookieList.add(a1Cookie);
aCookieList.add(a2Cookie);
HttpCookie bCookie = new HttpCookie("B", "b1");
List<HttpCookie> fakeCookieList = new ArrayList<>();
fakeCookieList.add(bCookie);
fakeCookieList.addAll(aCookieList);
ToBeMocked theSpy = spy(new ToBeMocked());
System.out.println("+++ 111 test(), aCookieList:"+aCookieList+", bCookie:"+bCookie);
//when(theSpy.mergeList(any(List.class), any(HttpCookie.class)))
when(theSpy.mergeList(eq(aCookieList), any(HttpCookie.class))). //<== exception on this
.thenReturn(fakeCookieList);
System.out.println("+++ 222 test()");
// test
// it would call some other function which internally call the mergeList(aCookieList, bCookie), and expect to generate a list from the stubbed result to use, here just make it simple to be run able to show the problem
List<HttpCookie> list = theSpy.mergeList(aCookieList, bCookie);
// verify
assertEquals(list.contains(bCookie), true);
}
在when(theSpy.mergeList(any(List.class), any(HttpCookie.class))).thenReturn(fakeCookieList); 上遇到异常NullPointerException。
日志显示两行:
Called loadFromPath(/system/framework/framework-res.apk, true); mode=binary sdk=28
+++ 111 test(), aCookieList:[A1="a1", A2="a2"], bCookie:B="b1"
+++ mergeList(), cookies:null, oneCookie:null
java.lang.NullPointerException
显然,mergeList() 使用空参数执行,并在
for (HttpCookie cookie : cookies)
问题:
认为 when().thenReturn() 只是用于设置存根,也就是说,当使用任何参数(或特定参数)调用 mock 的 mergeList() 时,它应该返回提供的列表。
when().thenReturn() 没有正确的参数吗? 为什么似乎在when().thenReturn()中执行了mergeList()?
【问题讨论】:
标签: java unit-testing mockito