Search code examples
spring-testrequest-mappingspring-restdocs

Only when testing: No mapping found for HTTP request


I use Spring Rest Docs in version 1.1.2.RELEASE

The Test

MvcResult result = this.mockMvc.perform(get("/api").accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andDo(print())
                .andDo(document("index"))
                .andReturn();

The API

@RequestMapping(value = "/api")
    public ResponseEntity<String> apiWelcome() {
        final HttpHeaders httpHeaders= new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        return new ResponseEntity<String>("{\"api\": \"test1\"}", httpHeaders, HttpStatus.OK);
    }

When I run the application I can access "/api" in the browser and get the expected {"api": "test1"} response.

But if I run the test I get the following log entries:

c.i.crawler.testnet.measure.RestDocsTest INFO  Started RestDocsTest in 2.96 seconds
o.s.web.servlet.PageNotFound WARN  No mapping found for HTTP request with URI [/api] in DispatcherServlet with name '' [main] 

and the test fails because of HTTP/1.1 404 Not Found. What am I doing wrong?

Application start

@SpringBootApplication
@Configuration
@EnableConfigurationProperties
@EnableAutoConfiguration
@ComponentScan(basePackageClasses = { SomeController.class })
public class AppRUN {

    public static void main(String[] args) {
        SpringApplication.run(AppRUN.class, args);
    }

} 

Solution

  • My test class was annotated as follows:

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(classes=RestDocsTest.class)
    @WebAppConfiguration
    

    Changing the annotations to the following removes the error:

    @RunWith(SpringRunner.class)
    @SpringBootTest