简体   繁体   English

使用 mockMvc 从 Spring Controller 断言返回项列表

[英]Asserting list of return items from Spring Controller with mockMvc

I've set up a spring boot application to use a Spring MVC controller to return a list of items.我已经设置了一个 Spring Boot 应用程序来使用 Spring MVC 控制器来返回一个项目列表。 I have a spring test that creates a mocked dependency that gets wired in to the Controller, and the controller returns the list of expected mocked items as a JSON array.我有一个 spring 测试,它创建了一个连接到控制器的模拟依赖项,控制器将预期的模拟项列表作为 JSON 数组返回。

I'm trying to assert that the content is correct simply.我试图断言内容是正确的。 I want to assert that the JSON array contains the expected list.我想断言 JSON 数组包含预期的列表。 I think there's a problem trying to interpret the JSON array as a java.util.List.我认为尝试将 JSON 数组解释为 java.util.List 时存在问题。 Is there a way to do this?有没有办法做到这一点?

The first and second .andExpect() pass, however, the hasItems() checks do not pass.第一次和第二次.andExpect()通过,但是hasItems()检查没有通过。 What can I do so I can just pass in my List<T> and verify it's contained in the JSON?我该怎么做才能传入我的List<T>并验证它是否包含在 JSON 中? The alternative I can think of is to conver the JSON to my List<T> and verify it using "regular java junit assertions"我能想到的替代方法是将 JSON 转换为我的List<T>并使用“常规 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();
        
    }
}

You could try something like this:你可以尝试这样的事情:

.andExpect(MockMvcResutMatchers.content().json(convertObjectToJsonString(mStudentList)));

And you can have a method that creates JSON from a list:你可以有一个从列表中创建 JSON 的方法:

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

You can modify the convertObjectToJsonString method to accepts Student object as a parameter (if you need one specific element in response).您可以修改convertObjectToJsonString方法以接受 Student 对象作为参数(如果您需要一个特定元素作为响应)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM