1

Could somebody tell me what is wrong in the following test?

shouldThrowNotAuthorizedException works fine, but the test for shouldCreateUser returns a HTTP status code 400.

UserControllerTest:

@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);
}

Exception

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

What's wrong with this test?

Stacktrace:

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)

Also I noticed some warnings in logs:

     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 ''
mtotowamkwe
  • 835
  • 6
  • 13
dante
  • 353
  • 14
  • 26

1 Answers1

1

Why are you having @RequestBody in RequestMethod Get. only for POST, input will be sent as part of the request body . For your information : 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.

please remove @RequestBody or else make it post request and try.

Community
  • 1
  • 1
Barath
  • 4,464
  • 1
  • 13
  • 37