使用MockMvc声明来自Spring Controller的返回项列表

Ste*_*bbi 6 java spring json spring-mvc spring-test

我已经设置了一个Spring Boot应用程序,以使用Spring MVC控制器返回项目列表。我有一个弹簧测试,它创建了一个模拟的依赖关系,该依赖关系被连接到Controller中,并且控制器以JSON数组的形式返回了预期的模拟项的列表。

我试图断言内容是正确的。我想断言JSON数组包含预期的列表。我认为尝试将JSON数组解释为java.util.List存在问题。有没有办法做到这一点?

first和second .andExepct()通过,但是hastItems()检查没有通过。我该怎么办,我可以只传递我的List并验证它是否包含在JSON中?我可以想到的替代方法是将JSON转换为我的List并使用“常规java junit断言”进行验证

public class StudentControllerTest extends AbstractControllerTest {

@Mock
private StudentRepository mStudentRepository;

@InjectMocks
private StudentController mStudentController;

private List<Student> mStudentList;


@Before
public void setUp() {
    MockitoAnnotations.initMocks(this);

    setUp(mStudentController);

    // mock the student repository to provide a list of 3 students.
    mStudentList = new ArrayList<>();
    mStudentList.add(new Student("Egon Spengler", new Date(), "111-22-3333"));
    mStudentList.add(new Student("Peter Venkman", new Date(), "111-22-3334"));
    mStudentList.add(new Student("Raymond Stantz", new Date(), "111-22-3336"));
    mStudentList.add(new Student("Winston Zeddemore", new Date(), "111-22-3337"));

    when(mStudentRepository.getAllStudents()).thenReturn(mStudentList);
}


@Test
public void listStudents() throws Exception {
    MvcResult result =
        mockMvc.perform(get("/students/list"))
        .andDo(print())
        .andExpect(jsonPath("$", hasSize(mStudentList.size())))
        .andExpect(jsonPath("$.[*].name", hasItems("Peter Venkman", "Egon Spengler", "Raymond Stantz", "Winston Zeddemore")))

        // doesn't work
        .andExpect(jsonPath("$.[*]", hasItems(mStudentList.toArray())))
        // doesn't work
        .andExpect(jsonPath("$.[*]", hasItems(mStudentList.get(0))))

        .andExpect(status().isOk())
            .andReturn();


    String content = result.getResponse().getContentAsString();


}
Run Code Online (Sandbox Code Playgroud)

}

小智 1

你可以尝试这样的事情:

.andExpect(MockMvcResutMatchers.content().json(convertObjectToJsonString(mStudentList)));
Run Code Online (Sandbox Code Playgroud)

您可以使用一个从列表创建 JSON 的方法:

 private String convertObjectToJsonString(List<Student> studentList) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            return mapper.writeValueAsString(studentList);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }
Run Code Online (Sandbox Code Playgroud)

您可以修改该convertObjectToJsonString方法以接受 Student 对象作为参数(如果您需要一个特定元素作为响应)。