gpt4 book ai didi

java - Spring Boot 测试 (MockMvc) - 收到 HTTP 状态代码 400,预计为 200

转载 作者:行者123 更新时间:2023-11-30 06:55:57 25 4
gpt4 key购买 nike

有人可以告诉我下面的测试出了什么问题吗?

shouldThrowNotAuthorizedException 工作正常,但 shouldCreateUser 的测试返回 HTTP 状态代码 400.

用户 Controller 测试:

@RunWith(SpringJUnit4ClassRunner.class)
@WebMvcTest(UserController.class)
public class UserControllerTest extends BaseControllerTest {

@Autowired
private MockMvc mvc;

@MockBean
private UserService userService;


@Before
public void setUp(){
mvc = MockMvcBuilders.standaloneSetup(UserController.class)
.setControllerAdvice(new ExceptionControllerAdvice())
.build();
}

@Test
public void shouldThrowNotAuthorizedException () throws Exception {

UserCredentialsDTO userCredentialsDTO = createRandomUserCredentialsDTO();
Gson gson = getGsonInstance();

given(this.userService.isAuthorized(userCredentialsDTO)).willThrow(NotAuthorizedException.class);

this.mvc.perform(MockMvcRequestBuilders.get("/user/authorize")
.accept(MediaType.APPLICATION_JSON)
.content(gson.toJson(userCredentialsDTO)))
.andExpect(MockMvcResultMatchers.status().is4xxClientError());
}

@Test
public void shouldCreateUser() throws Exception {

Gson gson = getGsonInstance();
UserCredentialsDTO userCredentialsDTO = createRandomUserCredentialsDTO();

given(this.userService.create(userCredentialsDTO)).willReturn(ResponseEntity.ok(userCredentialsDTO));

this.mvc.perform(MockMvcRequestBuilders.post("/user")
.accept(MediaType.APPLICATION_JSON)
.content(gson.toJson(userCredentialsDTO)))
.andExpect(MockMvcResultMatchers.status().is2xxSuccessful())
.andExpect(MockMvcResultMatchers.content().json(gson.toJson(userCredentialsDTO)));
}

private SuperUser createSuperUser(UserCredentialsDTO userCredentialsDTO) {
SuperUser user = new SuperUser();
user.setUserName(userCredentialsDTO.getUserName());
user.setPassword(userCredentialsDTO.getPassword());
return user;
}

private UserCredentialsDTO createRandomUserCredentialsDTO() {
UserCredentialsDTO userCredentialsDTO = new UserCredentialsDTO();
userCredentialsDTO.setUserName("Test");
userCredentialsDTO.setPassword("GGGaaa@@4");
userCredentialsDTO.setUserRole(UserRole.CUSTOMER);
return userCredentialsDTO;
}



}

用户 Controller :

@RestController
@RequestMapping(value = "/user")
public class UserController {

@Autowired
private UserService userService;

@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<UserCredentialsDTO> createUser(@RequestBody UserCredentialsDTO userCredentialsDTO) {
return userService.create(userCredentialsDTO);
}

@RequestMapping(value = "/authorize", method = RequestMethod.GET)
public ResponseEntity<UserCredentialsDTO> authorizeUser(@RequestBody UserCredentialsDTO userCredentialsDTO) {
return userService.isAuthorized(userCredentialsDTO);
}

UserServiceImpl:

@Override
public ResponseEntity<UserCredentialsDTO> create(UserCredentialsDTO userCredentialsDTO) {

User user = null;

switch (userCredentialsDTO.getUserRole()) {
case SUPER_USER:
user = new SuperUser();
break;
case CUSTOMER:
user = new Customer();
break;
}

user.setPassword(userCredentialsDTO.getPassword());
user.setUserName(userCredentialsDTO.getUserName());

userRepository.save(user);

return ResponseEntity.ok(userCredentialsDTO);
}

异常

java.lang.AssertionError: Range for response status value 404 
Expected :SUCCESSFUL
Actual :CLIENT_ERROR

这个测试有什么问题吗?

堆栈跟踪:

java.lang.AssertionError: Range for response status value 404 
Expected :SUCCESSFUL
Actual :CLIENT_ERROR
<Click to see difference>


at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:54)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:81)
at org.springframework.test.web.servlet.result.StatusResultMatchers$4.match(StatusResultMatchers.java:93)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:171)
at com.shoponline.controller.UserControllerTest.shouldCreateUser(UserControllerTest.java:75)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:237)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

我还注意到日志中的一些警告:

     main] o.s.web.servlet.PageNotFound             : No mapping found for  HTTP request with URI [/user/authorize] in DispatcherServlet with name ''
2017-01-23 22:03:22.955 INFO 1868 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.test.web.servlet.setup.StubWebApplicationContext@359b650b
2017-01-23 22:03:22.955 INFO 1868 --- [ main] .m.m.a.ExceptionHandlerExceptionResolver : Detected @ExceptionHandler methods in com.shoponline.controller.ExceptionControllerAdvice#6a9b0a6f
2017-01-23 22:03:22.955 INFO 1868 --- [ main] o.s.mock.web.MockServletContext : Initializing Spring FrameworkServlet ''
2017-01-23 22:03:22.955 INFO 1868 --- [ main] o.s.t.web.servlet.TestDispatcherServlet : FrameworkServlet '': initialization started
2017-01-23 22:03:22.965 INFO 1868 --- [ main] o.s.t.web.servlet.TestDispatcherServlet : FrameworkServlet '': initialization completed in 10 ms
2017-01-23 22:03:22.965 WARN 1868 --- [ main] o.s.web.servlet.PageNotFound : No mapping found for HTTP request with URI [/user] in DispatcherServlet with name ''

最佳答案

为什么在RequestMethod Get 中有@RequestBody。仅对于 POST,输入将作为请求正文的一部分发送。供您引用:HTTP GET with request body :

And the description of the GET method in the HTTP/1.1 spec, section 9.3: The GET method means retrieve whatever information ([...]) is identified by the Request-URI. which states that the request-body is not part of the identification of the resource in a GET request, only the request URI.

请删除@RequestBody,或者使其发布请求并尝试。

关于java - Spring Boot 测试 (MockMvc) - 收到 HTTP 状态代码 400,预计为 200,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41814518/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com