4

I have the following controller which accept input as @RequestParam

@RequestMapping(value = "/fetchstatus", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public Response fetchStatus(
        @RequestParam(value = "userId", required = true) Integer userId) {
    Response response = new Response();
    try {
        response.setResponse(service.fetchStatus(userId));
        response = (Response) Util.getResponse(
                response, ResponseCode.SUCCESS, FETCH_STATUS_SUCCESS,
                Message.SUCCESS);
    } catch (NullValueException e) {
        e.printStackTrace();
        response = (Response) Util.getResponse(
                response, ResponseCode.FAILED, e.getMessage(), Message.ERROR);
    } catch (Exception e) {
        e.printStackTrace();
        response = (Response) Util.getResponse(
                response, ResponseCode.FAILED, e.getMessage(), Message.ERROR);
    }
    return response;
}

I need a unit test class for this and I am beginner with spring mvc. I don't know writing test classes with @RequestParam as input.

Any help will be appreciated ..

Abhishek Ramachandran
  • 1,160
  • 1
  • 13
  • 34
  • Do you want to write a UNIT or an INTEGRATION test. If it is a unit test, just call the method like any other method. If you want an integration test use the Spring MVC testing support (see reference guide). – M. Deinum Sep 01 '16 at 09:42
  • Possible duplicate of [Mock MVC - Add Request Parameter to test](http://stackoverflow.com/questions/17972428/mock-mvc-add-request-parameter-to-test) – nowszy94 Sep 01 '16 at 09:43
  • what if the inputted parameter is an integer. It's showing .param() needs parameter as String. – Abhishek Ramachandran Sep 01 '16 at 11:54

2 Answers2

11

I solved this issue. I just changed the url. Now it contains the parameter as below in test class:

mockMvc.perform(get("/fetchstatus?userId=1").andExpect(status().isOk());
Abhishek Ramachandran
  • 1,160
  • 1
  • 13
  • 34
3

You can use MockMvc for testing Spring controllers.

@Test
public void testControllerWithMockMvc(){
  MockMvc mockMvc = MockMvcBuilders.standaloneSetup(controllerInstance).build();
  mockMvc.perform(get("/fetchstatus").requestAttr("userId", 1))
    .andExpect(status().isOk());
}

Also, it is possible to do it using pure JUnit, as long as you need to test only the logic inside your class

@Test
public void testControllerWithPureJUnit(){
  Controller controller = new Controller();
  //do some mocking if it's needed

  Response response = controller.fetchStatus(1);
  //asser the reponse from controller
}
Sergii Bishyr
  • 8,331
  • 6
  • 40
  • 69