最佳答案
I have a sample Spring Boot app with the following
Boot main 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's the easiest way to write a unit test for the controller? I tried the following but it complains about failing to autowire WebApplicationContext
@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() {
}
}