我正在通过样本from here编写测试。该测试旨在检查root用户名是否等于数据库中的用户名,并检查以下内容:

import static org.junit.Assert.*;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;

...

@Test
   public void rootUserPresent() throws Exception {

      ResultActions result = mockMvc.perform(get("/user/root"));

      result
         .andExpect(status().isOk())
         .andExpect(content().contentType(contentType))
         .andExpect(jsonPath("$.screenName", is(userRepository.getRootUser().getScreenName())))
         ;

   }


首先我写了这个测试,它导致ClassNotFound异常

java.lang.NoClassDefFoundError: com/jayway/jsonpath/InvalidPathException


因此,我当时以为系统希望向我报告错误的路径,但找不到异常的类。因此,我包括了com.jayway.jsonpath:json-path-assert:1.1.0依赖项。之后,测试才开始通过。

因此,我怀疑测试结果是错误的阳性。

我的问题是:如何使用与此处相同的工具显式提取JSON值,并从字面上检查其值?

聚苯乙烯

JSON结果如下:

{
   id: 1,
   roles: [
   {
      name: "USER"
   },
   {
      name: "ADMIN"
   }
],
   firstName: null,
   lastName: null,
   screenName: "root",
}

最佳答案

我做这样的事情:

// wrapper to extract result from the response
AssignmentResult result = new AssignmentResult();

// perform request
mockMvc.perform(
        get("/myApiEndpoint")
            .contentType(MediaType.APPLICATION_JSON)
            .accept(MediaType.APPLICATION_JSON)
        )
.andExpect(status().isOk())
    .andExpect(jsonPath("$object.parent.id", is(parent.getId())))
    .andDo(assignTo("$object.id", result)); // (**)

Integer objectIdFromResult = (Integer)result.getValue();    // (++)


assignTo是我编写的自定义ResultHandler:

/**
 * Spring ResultHandler for MVC testing, allows the assignment of a JSON path to a variable.
 */
public class AssignmentResultHandler implements ResultHandler {

    private final JsonPath jsonPath;
    private final AssignmentResult assignmentResult;

    public static ResultHandler assignTo(String jsonPath, AssignmentResult assignmentResult) {
        return new AssignmentResultHandler(JsonPath.compile(jsonPath), assignmentResult);
    }

    protected AssignmentResultHandler(JsonPath jsonPath, AssignmentResult assignmentResult) {
        this.jsonPath = jsonPath;
        this.assignmentResult = assignmentResult;
    }

    @Override
    public void handle(MvcResult result) throws Exception {
        String resultString = result.getResponse().getContentAsString();
        assignmentResult.setValue(jsonPath.read(resultString));
    }
}


创建新的AssignmentResultHandler时,将传入AssignmentResult包装器(**)。触发AssignmentResultHandler(运行handle)时,
它设置AssignmentResult的值。请求完成后,您可以从那里解包值(++)。

这是AssignmentResult包装器:

public class AssignmentResult {
    private Object value;

    /**
     * Set the result value
     * @param value result value
     */
    protected void setValue(Object value) {
        this.value = value;
    }

    /**
     * Returns the result value
     * @return the result value
     */
    public Object getValue() {
        return this.value;
    }
}

10-04 21:56