[英]Junit MockMvc perform POST with path variable in URL return 404 not found
我在 controller 中有一個 SpringBoot 應用程序使用此方法在數據庫中創建用戶。 controller 在 Postman 中工作正常。
@RestController
@RequestMapping("/v1")
public class UserController {
@PostMapping(value = "/user/{id}")
public void createUser(@PathVariable Integer id, @Valid @RequestBody User request,
BindingResult bindingResult) throws Exception {
if (bindingResult.hasErrors()) {
throw new RequestValidationException(VALIDATION_ERRORS, bindingResult.getFieldErrors());
}
userService.createUser(id, request), HttpStatus.CREATED);
}
現在我有一個 junit 測試用例來測試這個方法,我得到一個 404
@RunWith(SpringRunner.class)
@SpringBootTest(classes = MyApp.class)
public class UserTest {
private MockMvc mockMvc;
final String CREATE_USER_URL = "/v1/user/" + "10";
private final MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(),
MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));
@Test
public void testCreateUser() throws Exception {
mockMvc.perform(post(CREATE_USER_URL)
// doesn't work either if I put "/v1/user/10" or post("/v1/user/{id}", 10) here
.content(TestUtils.toJson(request, false))
.contentType(contentType))
.andDo(print())
.andExpect(status().isCreated())
.andReturn();
}
但在日志中,我能夠看到正確的 url:
模擬HttpServlet請求:
HTTP Method = POST
Request URI = /v1/user/10
Parameters = {}
有人可以告訴我為什么找不到 404 嗎? 謝謝。
從文檔中,您需要@AutoConfigureMockMvc
和@Autowire
MockMvc 上的 @AutoConfigureMockMvc
另一個有用的方法是根本不啟動服務器,而只測試它下面的層,其中 Spring 處理傳入的 HTTP 請求並將其交給您的 controller。 這樣,幾乎使用了完整的堆棧,並且調用代碼的方式與處理真正的 HTTP 請求的方式完全相同,但無需啟動服務器。 為此,我們將使用 Spring 的 MockMvc,我們可以通過在測試用例上使用 @AutoConfigureMockMvc 注釋來請求為我們注入它:
代碼:
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class UserTest {
@Autowire
private MockMvc mockMvc;
final String CREATE_USER_URL = "/v1/user/" + "10";
private final MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(),
MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));
@Test
public void testCreateUser() throws Exception {
mockMvc.perform(post(CREATE_USER_URL)
// doesn't work either if I put "/v1/user/10" or post("/v1/user/{id}", 10) here
.content(TestUtils.toJson(request, false))
.contentType(contentType))
.andDo(print())
.andExpect(status().isCreated())
.andReturn();
}
}
If want to Test your real springboot url Test (End to end Test)
u can use rest-assured or resttemplte
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Application.class)
@TestPropertySource(value={"classpath:application.properties"})
@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT)
public class SpringRestControllerTest {
@Value("${server.port}")
int port;
@Test
public void getDataTest() {
get("/api/tdd/responseData").then().assertThat().body("data", equalTo("responseData"));
}
@Before
public void setBaseUri () {
RestAssured.port = port;
RestAssured.baseURI = "http://localhost"; // replace as appropriate
}
}
https://dzone.com/articles/test-driven-development-with-spring-boot-rest-api
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.