Java – spring boot w / embedded Tomcat does not send requests to the controller
I have an application using spring boot and embedded Tomcat container
As far as I know, my code is the same as spring boot sample project However, when I run the test, I get a 404 instead of 200 (in the case of trying to release, instead of receiving a 405, which is consistent with the correct setting of Tomcat):
Failed tests: UserControllerTest.testMethod:45 Status expected:<200> but was:<404>
My java based configuration (some configuration classes are omitted):
@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"); } }; } }
UserController. 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()); } }
Is there anything basic I'm missing? I didn't provide my own MVC configuration, and I didn't encounter spring MVC dispatcher servlet, so I think spring boot will automatically configure Tomcat
Solution
The result is a problem with the component scan configuration Even if the @ componentscan annotation is used, the controller is in a separate package, so spring never includes it in the scheduler
Adding @ componentscan (basepackages = "com. My. Controller") solves my problem