【发布时间】:2019-07-04 06:12:06
【问题描述】:
我正在为我的一个控制器编写 API 测试用例,但结果是 404。 我认为这将是一个错字,但事实并非如此。下面是代码sn-ps。
RestController:package: com.x.y.address.controller (src/main)
@RestController
public class AddressInternalController {
@PostMapping(value = "/v1/address-service/internal/company/address", produces = "application/json;charset=UTF-8")
@ResponseStatus(OK)
public @ResponseBody ResponseEntity<AddressModel> createCompanyAddress()
throws AddressException, BadRequestException {
return ok("SUCCESS");
}
}
我的测试班:package com.x.y.address.controller (src/test)
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = TestApp.class, initializers = ConfigFileApplicationContextInitializer.class)
@WebMvcTest(controllers = AddressInternalController.class, secure = false)
public class AddressInternalControllerTest {
@Autowired
private MockMvc mvc;
@Before
public void init() {}
@Test
public void createAddressTest_when_invalid_company() throws Exception {
this.mvc.perform(post("/v1/address-service/internal/company/address").contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
}
}
我的应用程序使用 spring 安全性并绕过我创建了一个 TestAPP 类,这样它就可以帮助我只构建没有安全性的配置。
TestApp: 包 com.x.y.address (src/test)
@EnableAutoConfiguration(exclude = { SecurityAutoConfiguration.class})
// @ComponentScan({"com.x.y.address.controller.AddressInternalController"})
public class TestApp {
}
以上是类的结构。
最初我认为可能是程序没有扫描控制器包,因此没有扫描 404。因此添加了 componentScan。但这并没有帮助。
搜索了很多堆栈溢出,但大多数 404 是由于类型,但在我的情况下不是。
错误日志:
MockHttpServletRequest:
HTTP Method = POST
Request URI = /v1/address-service/internal/company/address
Parameters = {}
Headers = {Content-Type=[application/json]}
Body = <no character encoding set>
Session Attrs = {}
Handler:
Type = org.springframework.web.servlet.resource.ResourceHttpRequestHandler
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 404
Error message = null
Headers = {}
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
java.lang.AssertionError: Status
Expected :200
Actual :404
任何帮助将不胜感激。
【问题讨论】:
-
INTERNAL_ADDRESS_MAPPING的值是多少? -
哦,请忽略。我将编辑帖子。我将该值直接添加到 PostMapping
-
不应该
@ResponseStatus(OK)是@ResponseStatus(HttpStatus.OK)吗?
标签: spring-boot spring-test spring-boot-test