【发布时间】:2015-05-17 05:14:35
【问题描述】:
我有一个带有以下内容的示例 Spring Boot 应用程序
引导主类
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
控制器
@RestController
@EnableAutoConfiguration
public class HelloWorld {
@RequestMapping("/")
String gethelloWorld() {
return "Hello World!";
}
}
为控制器编写单元测试最简单的方法是什么?我尝试了以下方法,但它抱怨无法自动装配 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() {
}
}
【问题讨论】:
-
尝试用
@WebAppConfiguration注释DemoApplication。如果这不起作用,您可以添加它的代码吗?
标签: java unit-testing junit spring-boot spring-test-mvc