如何使用 MockMvcResultMatchers.jsonPath 验证 json 字段的格式是否正确?

Adg*_*aza 6 regex unit-testing spring-boot

我正在尝试使用正则表达式来验证值是否以特定方式格式化Lastname, Firstname(请参阅我进行格式断言的注释)。

我编写的测试使用 MockMvcResultMatchers。我找不到这个库的好的文档,我只能看到 API。因此,目前,我正在构建一个 ResultMatcher,jsonpath假设它将对模式匹配进行断言并返回一个布尔值。但它只返回我的值$.name

不确定我做错了什么。我粘贴了一个测试版本来演示我正在尝试做的事情。

import org.junit.Test;
import org.junit.runner.RunWith;

import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class SomeEntityControllerTests {

    @Autowired
    private MockMvc mockMvc;

    private Pattern name = Pattern.compile("^[A-Za-z0-9_']+\\s?,\\s?[A-Za-z0-9_']+$");

    @Test
    public void getSomeEntityShouldReturnOkWithProperlyFormatted() throws Exception {
        this.mockMvc.perform(get("/api/v1/someEntity/132")).andDo(print())
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.name").exists());
                .andExpect(jsonPath("$.name", matches(name))); // <-- FORMAT ASSERTION NOT WORKING. Only getting the string value of $.name
    }
}
Run Code Online (Sandbox Code Playgroud)

Ser*_*ero 7

使用 Hamcrest 库的 matchesPattern http://hamcrest.org/JavaHamcrest/javadoc/2.0.0.0/org/hamcrest/text/MatchesPattern.html

String regex = "^[A-Za-z0-9_']+\\s?,\\s?[A-Za-z0-9_']+$";

@Test
public void getSomeEntityShouldReturnOkWithProperlyFormatted() throws Exception {
    this.mockMvc.perform(get("/api/v1/someEntity/132")).andDo(print())
           .andExpect(status().isOk())
           .andExpect(jsonPath("$.name").exists());
           .andExpect(jsonPath("$.name", matchesPattern(regex)));
    }
Run Code Online (Sandbox Code Playgroud)