如何检查 mockMvc 响应 header 是否是我响应的一部分的 MD5 表示?

How do I check whether a mockMvc response header is the MD5 representation of a part of my response?

我需要将我的 mockMvc 响应 body 中特定值的 MD5 哈希值与同一请求的 header 进行比较。我不确定如何执行此操作,因为似乎没有一种简单的方法来获取 jsonPath 或 xPath 匹配器的内容。我认为像这样的东西是我设法得到的最接近的东西。我很确定我需要从 header 方面来解决这个问题,因为 MD5 不容易逆转。

mockMvc.perform(get(url)
                .session(session)
                .andExpect(header().string(ETAG,  convertToMD5(jsonPath("$.object.id"))));

有没有办法做到这一点,最好不要编写自定义匹配器?

深入研究 Spring MockMvc 使用的代码后,我发现最终 jsonPath().value(Object) ResultMatcher 在幕后使用 Object.equals(),特别是value 参数。因此,我发现最简单的方法是编写一个封装字符串 object 的 MD5Wrapper class 并定义一个自定义 equals 方法,该方法将封装的字符串与 MD5 哈希进行比较比较 object。

public class MD5Wrapper {
    private String mD5Hash;

    public MD5Wrapper(String md5Hash){
        mD5Hash = md5Hash;
    }

    public boolean equals(Object o2){
        if(o2 == null && mD5Hash == null){
            return true;
        }       
        if (o2 == null){
            return false;
        }
        if(mD5Hash == null){
            return false;
        }
        if(!(o2 instanceof String)){
            return false;
        }
        return org.apache.commons.codec.digest.DigestUtils.md5Hex((String)o2).equals(mD5Hash);
    }

    public String getmD5Hash() {
        return mD5Hash;
    }

    public String toString(){
        return mD5Hash;
    }

}

然后在测试本身中,我检索了我需要的 Etag header,将其包装并与我的 ID 进行比较:

ResultActions resultActions = mockMvc.perform(get("/projects/1")
    .session(session)
    .contentType(contentTypeJSON)
    .accept(MediaType.APPLICATION_JSON))
    .... //various accepts
    ;

MvcResult mvcResult = resultActions.andReturn();
String eTAG = mvcResult.getResponse().getHeader(ETAG);
resultActions.andExpect(jsonPath("$.id").value(new MD5Wrapper(eTAG.replace("\"", "")))); //our eTAG header is surrounded in double quotes, which have to be removed.

所以最后,我没有像我最初想的那样从 header 方面处理它,而是从 jsonPath 方面处理它。