How to write a unit test for a Spring Boot Controller endpoint

后端 未结 5 711
梦毁少年i
梦毁少年i 2020-12-07 12:22

I have a sample Spring Boot app with the following

Boot main class

@SpringBootApplication
public class DemoApplication {

    public static void mai         


        
5条回答
  •  一生所求
    2020-12-07 12:48

    The new testing improvements that debuted in Spring Boot 1.4.M2 can help reduce the amount of code you need to write situation such as these.

    The test would look like so:

    import static org.springframework.test.web.servlet.request.MockMvcRequestB‌​uilders.get; 
    import static org.springframework.test.web.servlet.result.MockMvcResultMat‌​chers.content; 
    import static org.springframework.test.web.servlet.result.MockMvcResultMat‌​chers.status;
    
        @RunWith(SpringRunner.class)
        @WebMvcTest(HelloWorld.class)
        public class UserVehicleControllerTests {
    
            @Autowired
            private MockMvc mockMvc;
    
            @Test
            public void testSayHelloWorld() throws Exception {
                this.mockMvc.perform(get("/").accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
                        .andExpect(status().isOk())
                        .andExpect(content().contentType("application/json"));
    
            }
    
        }
    

    See this blog post for more details as well as the documentation

提交回复
热议问题