Mockito 无效使用匹配器异常 [英] Mockito invalid use of Matchers exception
问题描述
我有以下一段代码,我正在使用 Mockito 为其编写单元测试:
I have the following piece of code for which I'm writing unit test using Mockito:
while (results.hasMore()) {
found = true;
SearchResult searchResult = (SearchResult) results.next();
Attributes attributes = searchResult.getAttributes();
Attribute attr = attributes.get(LdapAttribute.CUSTOMER_GUID.getValue());
setAttribute(attr);
if (getAttribute() != null && cust.getCstCustGuid() == null)
cust.setCstCustGuid((String) attr.get());
}
单元测试存根代码:
Mockito.doReturn(mockCustomer).when(ldap).getLDAPCustomer();
Mockito.doReturn(mockCtx).when(ldap).getInitialDirContext();
Mockito.doNothing().when(ldap).setAttribute(Mockito.any(Attribute.class));
Mockito.doReturn(mockAttribute).when(ldap).getAttribute();
Mockito.doReturn(mockSearchControls).when(ldap).getSearchControls();
Mockito.doNothing().when(mockSearchControls).setSearchScope(Mockito.anyInt());
Mockito.when(mockCtx.search(Mockito.anyString(), Mockito.anyString(), Mockito.any(SearchControls.class))).thenReturn(mockResults);
Mockito.when(mockResults.hasMore()).thenReturn(true).thenReturn(false);
Mockito.when(mockResults.next()).thenReturn(mockSearchResults);
Mockito.when(mockSearchResults.getAttributes()).thenReturn(mockAttributes);
Mockito.when(mockAttributes.get(Mockito.anyString())).thenReturn(mockAttribute);
Mockito.when(mockAttribute.get()).thenReturn(Mockito.anyObject());
Mockito.when(mockCustomer.getCstCustGuid()).thenReturn(Mockito.anyString());
Mockito.doNothing().when(mockCustomer).setCstCustGuid(Mockito.anyString());
我在该行收到 InvalidUseOfMatchers
异常:
I'm getting InvalidUseOfMatchers
exception at the line:
Mockito.when(mockCustomer.getCstCustGuid()).thenReturn(Mockito.anyString());
请帮忙.
推荐答案
您不能在 thenReturn()
中使用 Mockito.anyString()
.您只能在使用 Mockito.when()
或 Mockito.verify()
时使用它.示例:Mockito.when(mockCustomer.getSomething(Mockito.anyString())).thenReturn(something);
You cannot use Mockito.anyString()
inside a thenReturn()
. You can only use it when using Mockito.when()
or Mockito.verify()
.
Example: Mockito.when(mockCustomer.getSomething(Mockito.anyString())).thenReturn(something);
对于您的问题,您应该将 Mockito.when(mockCustomer.getCstCustGuid()).thenReturn(Mockito.anyString());
替换为
For your issue, you should replace the line Mockito.when(mockCustomer.getCstCustGuid()).thenReturn(Mockito.anyString());
by
Mockito.when(mockCustomer.getCstCustGuid()).thenReturn("");
或
Mockito.when(mockCustomer.getCstCustGuid()).thenReturn(Mockito.mock(String.class));
这篇关于Mockito 无效使用匹配器异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!