简体   繁体   English

Mockito无效使用Matchers异常

[英]Mockito invalid use of Matchers exception

I have the following piece of code for which I'm writing unit test using Mockito: 我有以下代码,我正在使用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());
      }

The unit test stub code: 单元测试存根代码:

    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());

I'm getting InvalidUseOfMatchers exception at the line: 我在这行获得了InvalidUseOfMatchers异常:

 Mockito.when(mockCustomer.getCstCustGuid()).thenReturn(Mockito.anyString());

Please help. 请帮忙。

You cannot use Mockito.anyString() inside a thenReturn() . 你不能在Mockito.anyString()使用thenReturn() You can only use it when using Mockito.when() or Mockito.verify() . 您只能在使用Mockito.when()Mockito.verify()时使用它。 Example: Mockito.when(mockCustomer.getSomething(Mockito.anyString())).thenReturn(something); 示例: Mockito.when(mockCustomer.getSomething(Mockito.anyString())).thenReturn(something);

For your issue, you should replace the line Mockito.when(mockCustomer.getCstCustGuid()).thenReturn(Mockito.anyString()); 对于您的问题,您应该替换Mockito.when(mockCustomer.getCstCustGuid()).thenReturn(Mockito.anyString()); by 通过

Mockito.when(mockCustomer.getCstCustGuid()).thenReturn(""); or 要么

Mockito.when(mockCustomer.getCstCustGuid()).thenReturn(Mockito.mock(String.class));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM