0

I have a method

public class ActivityManager {
    private ActivityManager activityManager_;

@Autowired
public ActivityManager(ActivityManager activityManage)
{
    activityManager_= activityManage;
}
@RequestMapping(value ="activityManager/", method = RequestMethod.GET)
   public List<Data> getData() throws RestControllerException {
        try {
            return activityManage_.fetchData();
        } catch (Exception ex) {
            throw new RestControllerException();
        }
     }
}

And I tried to test the throw exception but it does not work. I got confused into the case what's the status() for resultmatcher should be.

    @Test(expected = RestControllerException.class)
        public void getDataError() throws Exception {
           ActivityManager activityManagerMock = Mockito.mock(ActivityManager
                .class); 
doThrow(RestControllerException.class).when(activityManagerMock).fetchData();
            mockMvc_.perform(get("/activityManager")
                    .contentType(MediaType.APPLICATION_JSON))
        .andExpect(status().isInternalServerError());
        }

Is there any document that I can read more about handling exception for restapi unit test? Thanks

RLe
  • 456
  • 12
  • 28

1 Answers1

0
 @Autowired
    private ActivityManagerService activityManager;

This will inject the actual bean into the controller not the mock which you created.

Add this inside your test class.

@Autowired
private ControllerBean controller;

@Before
public void init(){
     ReflectionTestUtils.setField(controller, "activityManager", activityManagerMock);
}

This will set the MockObject into activityManager of Controller. And hence while running test the mock objects fetchData() will be called which inturn throws the exception.

Praneeth Ramesh
  • 3,434
  • 1
  • 28
  • 34