java - Mockito 无效使用 Matchers 异常

标签 java unit-testing 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());
      }

单元测试 stub 代码:

    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 异常:

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

请帮忙。

最佳答案

您不能在 thenReturn() 中使用 Mockito.anyString()。您只能在使用 Mockito.when()Mockito.verify() 时使用它。 示例:Mockito.when(mockCustomer.getSomething(Mockito.anyString())).thenReturn(something);

对于您的问题,您应该将行 Mockito.when(mockCustomer.getCstCustGuid()).thenReturn(Mockito.anyString()); 替换为

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

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

关于java - Mockito 无效使用 Matchers 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35128603/

相关文章:

java - 如何区分 javascript 中的 servlet 响应?

java.util.concurrent.ExecutionException : java. lang.OutOfMemoryError: Java 堆空间

javascript - 监视 jasmine 中的 jquery ui 小部件

Python 单元测试和发现

java - Mockito 验证另一个静态类中的发送邮件方法

java - 用于求解小模型的 Cplex Java

java - 在 Image View 上设置波纹效果

python - 在 Python 中测试时间敏感的应用程序

java - 如何在 Spring 测试中连接依赖关系

java - 如何在mockito中使用ArgumentCaptor