繁体   English   中英

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

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

我已经设置了一个 Spring Boot 应用程序来使用 Spring MVC 控制器来返回一个项目列表。 我有一个 spring 测试,它创建了一个连接到控制器的模拟依赖项,控制器将预期的模拟项列表作为 JSON 数组返回。

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

第一次和第二次.andExpect()通过,但是hasItems()检查没有通过。 我该怎么做才能传入我的List<T>并验证它是否包含在 JSON 中? 我能想到的替代方法是将 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();
        
    }
}

你可以尝试这样的事情:

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

你可以有一个从列表中创建 JSON 的方法:

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

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

暂无
暂无

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

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