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

后端 未结 5 707
梦毁少年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:37

    Here is another answer using Spring MVC's standaloneSetup. Using this way you can either autowire the controller class or Mock it.

        import static org.mockito.Mockito.mock;
        import static org.springframework.test.web.server.request.MockMvcRequestBuilders.get;
        import static org.springframework.test.web.server.result.MockMvcResultMatchers.content;
        import static org.springframework.test.web.server.result.MockMvcResultMatchers.status;
    
        import org.junit.Before;
        import org.junit.Test;
        import org.junit.runner.RunWith;
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.boot.test.context.SpringBootTest;
        import org.springframework.http.MediaType;
        import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
        import org.springframework.test.web.server.MockMvc;
        import org.springframework.test.web.server.setup.MockMvcBuilders;
    
    
        @RunWith(SpringJUnit4ClassRunner.class)
        @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
        public class DemoApplicationTests {
    
            final String BASE_URL = "http://localhost:8080/";
    
            @Autowired
            private HelloWorld controllerToTest;
    
            private MockMvc mockMvc;
    
            @Before
            public void setup() {
                this.mockMvc = MockMvcBuilders.standaloneSetup(controllerToTest).build();
            }
    
            @Test
            public void testSayHelloWorld() throws Exception{
                //Mocking Controller
                controllerToTest = mock(HelloWorld.class);
    
                 this.mockMvc.perform(get("/")
                         .accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
                         .andExpect(status().isOk())
                         .andExpect(content().mimeType(MediaType.APPLICATION_JSON));
            }
    
            @Test
            public void contextLoads() {
            }
    
        }
    

提交回复
热议问题