1 回答

TA貢獻1871條經驗 獲得超13個贊
我在嘗試模擬 NamingEnumeration 時遇到問題。
考慮改用真正的枚舉?;旧希鷳撝荒M自己創建的過于復雜的對象(列表、迭代器和枚舉是不復雜對象的示例)。
此外,我無法覆蓋到 lambda 表達式內部。
它按預期工作。您模擬(讀取替換)了搜索方法,因此沒有對 lambda 表達式的求值,因為它已經具有定義的結果。
while 循環似乎認為 NamingEnumeration 是空的,因為沒有覆蓋。
以下結果導致“在測試類中檢測到不必要的存根”:doReturn(true,false).when(enumeration).hasMore(); 和 doReturn(attr).when(enumeration).next();
hasMore 和 next 是您的拼寫錯誤,因為您的示例中調用的方法是 hasMoreElements 和 nextElement。
@Test
public void addToList() throws NamingException {
doReturn(true,false).when(enumeration).hasMoreElements();
doReturn(attr).when(enumeration).nextElement();
Assert.assertNotNull(ldapQueryDaoImpl.addToList(enumeration));
}
您可以單獨驗證 lambda 表達式,示例如下:
class MyMatcher implements AttributesMapper<Attributes> {
List<MyObject> list = new ArrayList<>();
public Attributes mapFromAttributes(Attributes attrs) {
NamingEnumeration<?> enumeration = attrs.get(key).getAll();
list.addAll(addToList(enumeration));
return attrs;
}
}
public void test() {
NamingEnumeration<? extends Attribute> enumeration = ...
Attribute attributeMock = mock(Attribute.class);
when(attributeMock.getAll()).thenReturn(enumeration);
Attributes attributesMock = mock(Attributes.class);
when(attributesMock.get(any(String.class)).thenReturn(attributeMock);
MyMatcher matcher = new MyMatcher();
matcher.mapFromAttributes(attr);
// assert ... matcher.list
}
添加回答
舉報