【发布时间】:2014-04-28 03:11:45
【问题描述】:
我有一个使用 spring-boot 和嵌入式 Tomcat 容器的应用程序。
据我所知,我的代码与 spring-boot sample project 相同。但是,当我运行测试时,我得到的是 404 而不是 200(在我尝试发布而不是获取的情况下,我收到 405,这与 Tomcat 设置不正确一致):
Failed tests:
UserControllerTest.testMethod:45 Status expected:<200> but was:<404>
我的基于 Java 的配置(省略了一些配置类):
@Configuration
@ComponentScan
@EnableAutoConfiguration
@Import({ ServiceConfig.class, DefaultRepositoryConfig.class })
public class ApplicationConfig {
private static Log logger = LogFactory.getLog(ApplicationConfig.class);
public static void main(String[] args) {
SpringApplication.run(ApplicationConfig.class);
}
@Bean
protected ServletContextListener listener() {
return new ServletContextListener() {
@Override
public void contextInitialized(ServletContextEvent sce) {
logger.info("ServletContext initialized");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
logger.info("ServletContext destroyed");
}
};
}
}
用户控制器.java:
@RestController
@RequestMapping("/")
public class UserController {
@Autowired
UserService userService;
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<String> testMethod() {
return new ResponseEntity<>("Success!", HttpStatus.OK);
}
}
UserControllerTest.java:
RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = {ApplicationConfig.class})
public class UserControllerTest {
@Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
@Before
public void setUp() throws Exception {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build();
}
@Test
public void testMethod() throws Exception {
this.mockMvc.perform(get("/")).andExpect(status().isOk());
}
}
我缺少一些基本的东西吗?我没有提供自己的 MVC 配置,也没有接触过 Spring MVC DispatcherServlet,所以我假设 spring-boot 会自动配置 Tomcat。
【问题讨论】:
-
您的问题并未详细说明您的问题到底是什么。我看到你提到
405而不是404。但是您引用的结果显示了其他内容。请详细说明问题是什么,涉及的条件是什么以及预期的结果 -
我已将我的问题编辑得更清楚。本质上,我希望我的 JUnit testMethod() 能够访问 UserController.testMethod()。结果应该是 200 并且编译成功。
-
405 是正确的并且是预期的,不是吗?不确定 404,但是当您启动上下文时(可能在调试中),您应该会看到您的映射已在日志中注册。它通常会为您提供有关映射的完整报告。
-
有关信息:如果您在 Spring Boot 应用程序中使用
@SpringApplicationConfiguration而不是@ContextConfiguration会有所帮助(确保您在启动应用程序上下文时获得所有相同的功能)。在这里与我们所看到的没有任何区别,并且相同形式的简单应用程序对我有用,所以我怀疑您隐藏了一些重要的东西。如果你能发布整个项目会有帮助。 -
我还没有看到@SpringApplicationConfiguration,谢谢你的提示。
标签: java spring tomcat spring-boot