有人可以告诉我下面的测试我做错了什么吗? shouldThrowNotAuthorizedException 工作正常,但测试方法 shouldCreateUser 会返回状态400
UsreControllerTest:
@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;
}
}
UserController中:
@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 ''
答案 0 :(得分:0)
为什么在RequestMethod Get中有@RequestBody。仅对于POST,输入将作为请求正文的一部分发送。 有关您的信息:HTTP GET with request body:
HTTP / 1.1规范中的GET方法的说明,第9.3节: GET方法意味着检索Request-URI标识的任何信息([...])。 表明请求主体不是GET请求中资源标识的一部分,只是请求URI。
请删除@RequestBody或者让它发布请求并尝试。