我正在尝试为我的 Spring Boot 应用程序添加单元测试。它不起作用,并抛出 404。我使用的是 1.2.1 版本的 spring boot,并且依赖于 spring-boot-starter-test。如果我遗漏了什么,请告诉我。春季启动应用程序可以正常工作。
这是我的代码,
public class Application{
public static void main(String[] args) {//NOSONAR
SpringApplication.run(Application.class, args);
}
@Bean
public ServletRegistrationBean displayListServletRegistrationBean(){
return new ServletRegistrationBean(new DisplayServlet(),"/display");
}
@Bean
public ServletRegistrationBean manageServletRegistrationBean(){
return new ServletRegistrationBean(new ManageServlet(),"/manage");
}
}
我的junit测试用例代码,
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:application-test-context.xml"})
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
@WebIntegrationTest({"server.port=0", "management.port=0"})
@ActiveProfiles("scratch")
public class ApplicationTest {
@Autowired
private WebApplicationContext context;
private MockMvc mvc;
@Before
public void setUp() {
this.mvc = MockMvcBuilders.webAppContextSetup(this.context).build();
}
@Test
public void testHome() throws Exception {
this.mvc.perform(get("/display")).andExpect(status().isOk());
//this.mvc.perform(get("/")).andExpect(status().isOk());
}
}
控制台有
org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/display] in DispatcherServlet with name ''
和 Junit 结果有
java.lang.AssertionError: Status expected:<200> but was:<404> at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:60)