classCastException in Mockito with Java.lang.String



我有以下一段代码,我正在使用 Mockito 编写单元测试

 if (user != null) {
        LDAPCustomer cust = getLDAPCustomer();
        LDAPAuthorization auth = getLDAPAuthorization();
        cust = getCustomerData( new LDAPInstruction(SearchType.EQUAL_TO, LdapAttribute.CUSTOMER_MAIL, user));
        if (cust != null)
            auth = getAuthorizationData(new LDAPInstruction(SearchType.EQUAL_TO, LdapAttribute.AUTHORIZATION_GUID, cust.getCstAuthGuid()));
        if (cust != null && auth!= null && cust.getCstManageeGuids().size() == 1) {
            String custGuid = cust.getCstCustGuid();
            if (cust.getCstManageeGuids().get(0).equals(custGuid)) {
                //No secondary user
                try
                {
                    deleteUserAssociations(cust.getCstCustGuid());
                    resetAuthorization(auth.getCstAuthGuid());
                    logger.info(cust.getCstCustGuid()+" user successfully perged.");
                } catch (Exception e) {
                    logger.error("Error occured whie try to purging user: "+MiscUtility.getStackTrace(e));
                    throw new Exception("Error occured whie try to purging user: "+e.getMessage());
                }
            }
        }
    }

这是模拟代码

 int size = 1;
    //Define the Stub
    Mockito.doReturn(mockCustomer).when(ldap).getLDAPCustomer();
    Mockito.doReturn(mockAuthorization).when(ldap).getLDAPAuthorization();
    Mockito.doReturn(mockCustomer).when(ldap).getCustomerData(Mockito.any(LDAPInterface.LDAPInstruction.class));
    Mockito.doReturn(mockAuthorization).when(ldap).getAuthorizationData(Mockito.any(LDAPInterface.LDAPInstruction.class));
    Mockito.when(mockCustomer.getCstManageeGuids().size()).thenReturn(size);
    Mockito.when(mockCustomer.getCstCustGuid()).thenReturn("mockCust");
    Mockito.when(mockCustomer.getCstManageeGuids().get(Mockito.anyInt()).equals(Mockito.eq("mockCust"))).thenReturn(true);
    Mockito.doNothing().when(ldap).deleteUserAssociations(Mockito.anyString());
    Mockito.doNothing().when(ldap).resetAuthorization(Mockito.anyString());

我得到一个类投射异常,如下所示

java.lang.ClassCastException: org.mockito.internal.creation.jmock.ClassImposterizer$ClassWithSuperclassToWorkAroundCglibBug$$EnhancerByMockitoWithCGLIB$$1ebf8eb1 cannot be cast to java.lang.String

在生产线上

 Mockito.when(mockCustomer.getCstManageeGuids().get(Mockito.anyInt()).equals(Mockito.eq("mockCust"))).thenReturn(true);

感谢任何帮助。

通过打破链条来解决它。

    List<String> lst = new ArrayList<String>();
    lst.add("mockVal");
    Mockito.when(mockCustomer.getCstManageeGuids()).thenReturn(lst);

相关内容

  • 没有找到相关文章

最新更新