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

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

    Spring MVC offers a standaloneSetup that supports testing relatively simple controllers, without the need of context.

    Build a MockMvc by registering one or more @Controller's instances and configuring Spring MVC infrastructure programmatically. This allows full control over the instantiation and initialization of controllers, and their dependencies, similar to plain unit tests while also making it possible to test one controller at a time.

    An example test for your controller can be something as simple as

    public class DemoApplicationTests {
    
        private MockMvc mockMvc;
    
        @Before
        public void setup() {
            this.mockMvc = standaloneSetup(new HelloWorld()).build();
        }
    
        @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"));
    
        }
    }
    

提交回复
热议问题