How to check String in response body with mockMvc

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

I have simple integration test

@Test
public void shouldReturnErrorMessageToAdminWhenCreatingUserWithUsedUserName()          


        
12条回答
  •  鱼传尺愫
    2020-12-02 04:39

    One possible approach is to simply include gson dependency:

    
        com.google.code.gson
        gson
    
    

    and parse the value to make your verifications:

    @RunWith(SpringRunner.class)
    @WebMvcTest(HelloController.class)
    public class HelloControllerTest {
    
        @Autowired
        private MockMvc mockMvc;
    
        @MockBean
        private HelloService helloService;
    
        @Before
        public void before() {
            Mockito.when(helloService.message()).thenReturn("hello world!");
        }
    
        @Test
        public void testMessage() throws Exception {
            MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/"))
                    .andExpect(status().isOk())
                    .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON_VALUE))
                    .andReturn();
    
            String responseBody = mvcResult.getResponse().getContentAsString();
            ResponseDto responseDto
                    = new Gson().fromJson(responseBody, ResponseDto.class);
            Assertions.assertThat(responseDto.message).isEqualTo("hello world!");
        }
    }
    

提交回复
热议问题