I have a sample Spring Boot application with the following
Main loading class
@SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); }
controller
@RestController @EnableAutoConfiguration public class HelloWorld { @RequestMapping("/") String gethelloWorld() { return "Hello World!"; } }
What is the easiest way to write unit test for a controller? I tried the following, but he complains that WebApplicationContext was not able to auto-increment
@RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = DemoApplication.class) public class DemoApplicationTests { final String BASE_URL = "http://localhost:8080/"; @Autowired private WebApplicationContext wac; private MockMvc mockMvc; @Before public void setup() { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).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")); } @Test public void contextLoads() { } }
java spring-boot spring-test-mvc unit-testing junit
user6123723 Mar 14 '15 at 20:43 2015-03-14 20:43
source share