【问题标题】:Junit test case AssertionError expected to be a json stringJunit 测试用例 AssertionError 应为 json 字符串
【发布时间】:2019-09-19 22:22:54
【问题描述】:

我正在尝试创建一个辅助方法来将 MockMvc 测试的响应主体转换回我的域对象,并希望使其适用于所有对象。它在响应是一个对象时起作用,但在它是对象列表时不起作用。

我正在使用 com.fasterxml.jackson.databind.ObjectMapper 和 com.fasterxml.jackson.core.type.TypeReference 将响应主体映射回我的应用程序对象。

这些是将响应映射到对象的方法:

  protected static <T> List<T> getResponseBodyList(MockHttpServletResponse response,
      Class<T> clazz) throws JsonParseException, JsonMappingException,
      UnsupportedEncodingException, IOException, InstantiationException, IllegalAccessException {
    TypeReferenceListImpl<T> typeReference = new TypeReferenceListImpl<T>(clazz);
    List<T> responseBody = new ObjectMapper().readValue(response.getContentAsString(),
        typeReference);
    return (List<T>) responseBody;
  }

  protected static <T> T getResponseBody(MockHttpServletResponse response, Class<T> clazz)
      throws JsonParseException, JsonMappingException, UnsupportedEncodingException, IOException {
    TypeReferenceImpl<T> typeReference = new TypeReferenceImpl<T>(clazz);
    T responseBody = new ObjectMapper().readValue(response.getContentAsString(), typeReference);
    return responseBody;
  }

  private static class TypeReferenceImpl<T> extends TypeReference<T> {
    protected final Type type;

    protected TypeReferenceImpl(Class<T> clazz) {
      type = clazz;
    }

    public Type getType() {
      return type;
    }
  }

  private static class TypeReferenceListImpl<T> extends TypeReference<T> {
    protected final Type type;

    protected TypeReferenceListImpl(Class<T> clazz) throws InstantiationException,
        IllegalAccessException {
      List<T> list = new ArrayList<>();
      list.add(clazz.newInstance());
      type = list.getClass();
    }

    public Type getType() {
      return type;
    }
  }

我在测试中这样调用这些方法:

// This test works: 
  @Test
  public void getUserTest() throws Exception {
    when(applicationUserServiceMock.loadUserByUsername(applicationUser.getUsername())).thenReturn(
        applicationUser);

    MockHttpServletResponse response = executeGet(API_V1_ADMIN_APPLICATION_USERS + applicationUser
        .getUsername());
    ApplicationUser responseBody = getResponseBody(response, ApplicationUser.class);

    verifyResponseStatus(response, HttpStatus.OK.value());
    assertEquals(applicationUser, responseBody);
  }

//Test that fails:
 @Test
  public void getUsersTest() throws Exception {
    when(applicationUserServiceMock.getAllUsers()).thenReturn(applicationUsersList);

    MockHttpServletResponse response = executeGet(API_V1_ADMIN_APPLICATION_USERS); 

    List<ApplicationUser> responseBody = getResponseBodyList(response, ApplicationUser.class);

    verifyResponseStatus(response, HttpStatus.OK.value());
    assertEquals(3, responseBody.size()); // This assert passes
    assertEquals(applicationUsersList, responseBody); 
// Fails in the last assertEquals. Debugging it, I can see responseBody ends up being a List of LinkedHashMaps. 
// I assume because I get a list of Objects instead of a list of ApplicationUsers. 
  }

为此,我需要做的是(至少作为第一种方法),是让 TypeReferenceListImpl 返回 T 的真实类的列表类型,我将其作为参数 Class clazz 传递。但我似乎无法基于 Class 对象创建该特定类型的列表,以使用 getClass() 获取它的类型。这是我为获得这种类型而采取的许多方法中的最后一种,但没有一个奏效。

有可能吗?或者有人有其他方法来解决这个问题吗?

我正在尝试创建一个通用方法来获取所有控制器测试的响应主体,这些测试返回不同类型的对象列表

堆栈跟踪是:

java.lang.AssertionError: expected:<[{
  "id" : 1001,
  "username" : "goku",
  "password" : null,
  "email" : "goku@dbz.com",
  "firstName" : "Goku",
  "lastName" : "Son",
  "lastLogin" : null,
  "authorities" : [ {
    "id" : 10,
    "name" : "ADMIN_ROLE"
  } ],
  "accountNonExpired" : true,
  "accountNonLocked" : true,
  "credentialsNonExpired" : true,
  "enabled" : true
}, {
  "id" : 1002,
  "username" : "gohan",
  "password" : null,
  "email" : "gohan@dbz.com",
  "firstName" : null,
  "lastName" : null,
  "lastLogin" : null,
  "authorities" : [ {
    "id" : null,
    "name" : "ROLE_USER"
  } ],
  "accountNonExpired" : true,
  "accountNonLocked" : true,
  "credentialsNonExpired" : true,
  "enabled" : true
}, {
  "id" : 1003,
  "username" : "goten",
  "password" : null,
  "email" : "goten@dbz.com",
  "firstName" : null,
  "lastName" : null,
  "lastLogin" : null,
  "authorities" : [ {
    "id" : null,
    "name" : "ROLE_USER"
  } ],
  "accountNonExpired" : true,
  "accountNonLocked" : true,
  "credentialsNonExpired" : true,
  "enabled" : true
}]> but was:<[{id=1001, username=goku, password=null, email=goku@dbz.com, firstName=Goku, lastName=Son, lastLogin=null, authorities=[{id=10, name=ADMIN_ROLE}], accountNonExpired=true, accountNonLocked=true, credentialsNonExpired=true, enabled=true}, {id=1002, username=gohan, password=null, email=gohan@dbz.com, firstName=null, lastName=null, lastLogin=null, authorities=[{id=null, name=ROLE_USER}], accountNonExpired=true, accountNonLocked=true, credentialsNonExpired=true, enabled=true}, {id=1003, username=goten, password=null, email=goten@dbz.com, firstName=null, lastName=null, lastLogin=null, authorities=[{id=null, name=ROLE_USER}], accountNonExpired=true, accountNonLocked=true, credentialsNonExpired=true, enabled=true}]>
    at org.junit.Assert.fail(Assert.java:88)
    at org.junit.Assert.failNotEquals(Assert.java:834)
    at org.junit.Assert.assertEquals(Assert.java:118)
    at org.junit.Assert.assertEquals(Assert.java:144)
    at com.nicobrest.kamehouse.admin.controller.ApplicationUserControllerTest.getUsersTest(ApplicationUserControllerTest.java:91)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.junit.rules.ExpectedException$ExpectedExceptionStatement.evaluate(ExpectedException.java:239)
    at org.junit.rules.RunRules.evaluate(RunRules.java:20)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)
...

更新: 如果有人遇到这种情况,您不需要手动创建列表,jackson mapper 已经有一个内置的方法来创建您传递的泛型类型的列表(facepalm),所以我的最终解决方案是使用这两种方法:

  protected static <T> List<T> getResponseBodyList(MockHttpServletResponse response, Class<T> clazz)
      throws JsonParseException, JsonMappingException, UnsupportedEncodingException, IOException,
      InstantiationException, IllegalAccessException {
    ObjectMapper mapper = new ObjectMapper();
    List<T> responseBody = mapper.readValue(response.getContentAsString(),
        mapper.getTypeFactory().constructCollectionType(List.class, clazz));
    return responseBody;
  }

  protected static <T> T getResponseBody(MockHttpServletResponse response, Class<T> clazz)
      throws JsonParseException, JsonMappingException, UnsupportedEncodingException, IOException {
    ObjectMapper mapper = new ObjectMapper();
    T responseBody = mapper.readValue(response.getContentAsString(),
        mapper.getTypeFactory().constructType(clazz));
    return responseBody;
  }

感谢@deadpool 的建议,让我从不同的角度看待它

【问题讨论】:

    标签: java list generics


    【解决方案1】:

    问题是applicationUsersList 是一个json 字符串或者List&lt;JsonObject&gt;responseBodyList&lt;ApplicationUser&gt; 两者都不相等。使用ObjectMapperapplicationUsersList 转换为List&lt;ApplicationUser&gt;

    public <T> T readValue(String src,
              TypeReference valueTypeRef)
            throws IOException,
                   JsonParseException,
                   JsonMappingException
    

    或者您可以将List&lt;ApplicationUser&gt; 转换为json 字符串或List&lt;JsonObject&gt;

    public String writeValueAsString(Object value)
                          throws JsonProcessingException
    

    【讨论】:

    • 嗨@deadpool 感谢您调查问题。我忘了把它放在示例中,但 aplicationUsersList 实际上是 List 类型。这是声明 private static List applicationUsersList;我会采纳你的建议,看看我是否可以将两者都映射到 json 字符串或对象,以便通过使用字符串而不是 List 比较它们来使它们具有相同的格式。将返回结果
    • 嗨@deadpool 我接受了你的回答,因为它解决了我遇到的问题,但我选择了我在原始帖子中发布的不同解决方案,以防有人需要另一种方法。谢谢!
    猜你喜欢
    • 2019-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-08
    相关资源
    最近更新 更多