【问题标题】:Is there a method built in spring MockMVC to get json content as Object?spring MockMVC 中是否有一种方法可以将 json 内容作为对象获取?
【发布时间】:2019-01-23 05:04:30
【问题描述】:

在我的 Spring 项目中,我创建了一些检查控制器/http-api 的测试。有没有办法将响应的 json 内容作为反序列化对象获取?

在其他项目中,我使用了放心,并且有方法直接将结果作为预期对象。

这是一个例子:

    MvcResult result = rest.perform( get( "/api/byUser" ).param( "userName","test_user" ) )

            .andExpect( status().is( HttpStatus.OK.value() ) ).andReturn();
    String string = result.getResponse().getContentAsString();

该方法以 json 形式返回特定类型。如何将此 json 转换回对象以测试其内容? 我知道杰克逊或放心的方法,但在 spring/test/mockmvc 中有方法

点赞getContentAs(Class)

【问题讨论】:

  • 当你调用你的rets api时,spring会自动将它转换为Object。您可以指定调用时应转换为哪个对象。没有任何代码sn-ps就不能多说,
  • 添加了示例代码。

标签: json spring spring-mvc junit


【解决方案1】:

据我所知MockHttpServletResponse(与 RestTemplate 不同)没有任何方法可以将返回的 JSON 转换为特定类型。

所以你可以做的是使用 Jackson ObjectMapper 将 JSON 字符串转换为特定类型

类似的东西

String json = rt.getResponse().getContentAsString();
SomeClass someClass = new ObjectMapper().readValue(json, SomeClass.class);

这将使您有更多的控制权来断言不同的事情。

话虽如此,MockMvc::perform 返回ResultActions,它有一个方法andExpect 接受ResultMatcher。这有很多选项可以在不将其转换为对象的情况下测试生成的 json。

例如

mvc.perform(  .....
                ......
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.firstname").value("john"))
                .andExpect(jsonPath("$.lastname").value("doe"))
                .andReturn();

【讨论】:

  • 虽然可行,但它会创建一个 ObjectMapper 的新实例,该实例可能与配置的实例不同。您可能最好注入 Spring Boot 创建的一个。
  • @Deinum,是的,你是对的。但这只是我展示的一个例子。这取决于 OP 他想怎么做。仍然感谢您的意见。
【解决方案2】:

这可能有用:

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.togondo.config.database.MappingConfig;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultHandler;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Getter
public class CustomResponseHandler<T> implements ResultHandler {

private final Class<? extends Collection> collectionClass;
private T responseObject;
private String responseData;
private final Class<T> type;
private Map<String, String> headers;
private String contentType;

public CustomResponseHandler() {
    this.type = null;
    this.collectionClass = null;
}

public CustomResponseHandler(Class type) {
    this.type = type;
    this.collectionClass = null;
}

public CustomResponseHandler(Class type, Class<? extends Collection> collectionClass) {
    this.type = type;
    this.collectionClass = collectionClass;
}


protected <T> T responseToObject(MockHttpServletResponse response, Class<T> type) throws IOException {
    String json = getResponseAsContentsAsString(response);
    if (org.apache.commons.lang3.StringUtils.isEmpty(json)) {
        return null;
    }
    return MappingConfig.getObjectMapper().readValue(json, type);
}

protected <T> T responseToObjectCollection(MockHttpServletResponse response, Class<? extends Collection> collectionType, Class<T> collectionContents) throws IOException {
    String json = getResponseAsContentsAsString(response);
    if (org.apache.commons.lang3.StringUtils.isEmpty(json)) {
        return null;
    }
    ObjectMapper mapper = MappingConfig.getObjectMapper();
    JavaType type = mapper.getTypeFactory().constructCollectionType(collectionType, collectionContents);
    return mapper.readValue(json, type);
}


protected String getResponseAsContentsAsString(MockHttpServletResponse response) throws IOException {
    String content = "";
    BufferedReader br = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(response.getContentAsByteArray())));
    String line;
    while ((line = br.readLine()) != null)
        content += line;
    br.close();

    return content;
}

@Override
public void handle(MvcResult result) throws Exception {
    if( type != null ) {
        if (collectionClass != null) {
            responseObject = responseToObjectCollection(result.getResponse(), collectionClass, type);
        } else {
            responseObject = responseToObject(result.getResponse(), type);
        }
    }
    else {
        responseData = getResponseAsContentsAsString(result.getResponse());
    }

    headers = getHeaders(result);
    contentType = result.getResponse().getContentType();

    if (result.getResolvedException() != null) {
        log.error("Exception: {}", result.getResponse().getErrorMessage());
        log.error("Error: {}", result.getResolvedException());
    }
}

private Map<String, String> getHeaders(MvcResult result) {
    Map<String, String> headers = new HashMap<>();
    result.getResponse().getHeaderNames().forEach(
            header -> headers.put(header, result.getResponse().getHeader(header))
    );
    return headers;
}

public String getHeader(String headerName) {
    return headers.get(headerName);
}

public String getContentType() {
    return contentType;
}

}

然后像这样在你的测试中使用它:

CustomResponseHandler<MyObject> responseHandler = new CustomResponseHandler(MyObject.class);

mockMvc.perform(MockMvcRequestBuilders.get("/api/yourmom"))
            .andDo(responseHandler)
            .andExpect(status().isOk());


MyObject myObject = responseHandler.getResponseObject();

或者如果你想获取集合:

CustomResponseHandler<Set<MyObject>> responseHandler = new CustomResponseHandler(MyObject.class, Set.class);
.
.
.
Set<MyObject> myObjectSet = responseHandler.getResponseObject();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-30
    • 1970-01-01
    • 2013-05-04
    • 2011-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多