How to check String in response body with mockMvc

后端 未结 12 1892
遇见更好的自我
遇见更好的自我 2020-12-02 04:02

I have simple integration test

@Test
public void shouldReturnErrorMessageToAdminWhenCreatingUserWithUsedUserName()          


        
12条回答
  •  眼角桃花
    2020-12-02 04:43

    Spring security's @WithMockUser and hamcrest's containsString matcher makes for a simple and elegant solution:

    @Test
    @WithMockUser(roles = "USER")
    public void loginWithRoleUserThenExpectUserSpecificContent() throws Exception {
        mockMvc.perform(get("/index"))
                .andExpect(status().isOk())
                .andExpect(content().string(containsString("This content is only shown to users.")));
    }
    

    More examples on github

提交回复
热议问题