簡體   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