我想使用JUnuit和Mockito测试以下方法。
public Map<String, String> getUserACLDetails(final int userId, final int networkId, final List<String> privilegeNames)
{
final Map<String, String> privilegeNameValue = new HashMap<>();
final Object aclDataString = cbClient.get(String.valueOf(userId));
Map<String, String> aclData = null;
if (null != aclDataString && !aclDataString.equals(NULL))
{
aclData = gson.fromJson(aclDataString.toString(), new HashMap<String, String>().getClass());
}
for (String privilegeName : privilegeNames)
{
String innerMapKey = String.valueOf(networkId) + UNDER_SCORE + privilegeName;
if (aclData.containsKey(innerMapKey))
{
privilegeNameValue.put(privilegeName, aclData.get(innerMapKey));
}
}
return privilegeNameValue;
}
以下是测试用例 -
public void getUserACLDetailsWithReturnValueTest()
{
final int userId = 123;
final int networkId = 525;
List<String> privilegeNames = new ArrayList<>();
String privilegeName = "PRIVILEGE_ACCESS_VIEW";
String privilegeValue = "true";
privilegeNames.add(privilegeName);
Map<String, String> privilegeNameValues = new HashMap<>();
privilegeNameValues.put(privilegeName,privilegeValue);
Map<String, String> aclData = new HashMap<>();
aclData.put(String.valueOf(networkId) + "_" + privilegeName, privilegeValue);
privilegeName = "PRIVILEGE_ACCESS_EDIT";
privilegeValue = "false";
aclData.put(String.valueOf(networkId) + "_" + privilegeName, privilegeValue);
Mockito.when(couchbaseClient.get(String.valueOf(userId))).thenReturn(aclData);
assertEquals(privilegeNameValues, userAclDao.getUserACLDetails(userId, networkId, privilegeNames));
}
但是当我执行测试用例时,我收到以下错误 -
java.lang.AssertionError: expected: java.util.HashMap<{PRIVILEGE_CREATIVE_ACCESS_VIEW=true}> but was: java.util.HashMap<{PRIVILEGE_CREATIVE_ACCESS_VIEW=true}>
at org.junit.Assert.fail(Assert.java:93)
at org.junit.Assert.failNotEquals(Assert.java:647)
at org.junit.Assert.assertEquals(Assert.java:128)
at org.junit.Assert.assertEquals(Assert.java:147)
at com.zedo.nirvana.hriday.authorization.UserAclDaoCouchbaseImplTest.getUserACLDetailsWithReturnValueTest(UserAclDaoCouchbaseImplTest.java:153)
我无法理解这里出了什么问题。任何人都可以提供帮助。
答案 0 :(得分:1)
以下是正确的测试用例 -
public void getUserACLDetailsWithReturnValueTest() {
final int userId = 123;
final int networkId = 525;
List<String> privilegeNames = new ArrayList<>();
String privilegeName = "PRIVILEGE_CREATIVE_ACCESS_VIEW";
String privilegeValue = "true";
privilegeNames.add(privilegeName);
final Object aclDataString = "{\"525" + "_" + privilegeName + "\": \"" + privilegeValue + "\"}";
Map<String, String> privilegeNameValues = new HashMap<>();
privilegeNameValues.put(privilegeName, privilegeValue);
Mockito.when(couchbaseClient.get(String.valueOf(userId))).thenReturn(aclDataString);
assertEquals(privilegeNameValues, userAclDao.getUserACLDetails(userId, networkId, privilegeNames));
}
在调用模拟对象方法时返回值时,我犯了一个错误。