仅在测试时:未找到 HTTP 请求的映射
Only when testing: No mapping found for HTTP request
我用的是1.1版本的Spring Rest Docs2.RELEASE
测试
MvcResult result = this.mockMvc.perform(get("/api").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andDo(print())
.andDo(document("index"))
.andReturn();
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);
}
当我 运行 应用程序时,我可以在浏览器中访问“/api”并获得预期的 {"api": "test1"}
响应。
但是如果我 运行 测试我得到以下日志条目:
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]
并且测试失败是因为 HTTP/1.1 404 Not Found
。
我做错了什么?
应用程序启动
@SpringBootApplication
@Configuration
@EnableConfigurationProperties
@EnableAutoConfiguration
@ComponentScan(basePackageClasses = { SomeController.class })
public class AppRUN {
public static void main(String[] args) {
SpringApplication.run(AppRUN.class, args);
}
}
我的测试class注释如下:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=RestDocsTest.class)
@WebAppConfiguration
将注释更改为以下内容可消除错误:
@RunWith(SpringRunner.class)
@SpringBootTest
我用的是1.1版本的Spring Rest Docs2.RELEASE
测试
MvcResult result = this.mockMvc.perform(get("/api").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andDo(print())
.andDo(document("index"))
.andReturn();
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);
}
当我 运行 应用程序时,我可以在浏览器中访问“/api”并获得预期的 {"api": "test1"}
响应。
但是如果我 运行 测试我得到以下日志条目:
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]
并且测试失败是因为 HTTP/1.1 404 Not Found
。
我做错了什么?
应用程序启动
@SpringBootApplication
@Configuration
@EnableConfigurationProperties
@EnableAutoConfiguration
@ComponentScan(basePackageClasses = { SomeController.class })
public class AppRUN {
public static void main(String[] args) {
SpringApplication.run(AppRUN.class, args);
}
}
我的测试class注释如下:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=RestDocsTest.class)
@WebAppConfiguration
将注释更改为以下内容可消除错误:
@RunWith(SpringRunner.class)
@SpringBootTest