I want to write unit test cases for negative scenarios for my REST API spring boot application.
The controller methods looks like this:
@RequestMapping(path = "/getcalc/srn/{srn}", method = RequestMethod.GET)
public RestResponse<List<BookMarkMRPostProcessCalc>> fetchLatestPostProcessCalc(@PathVariable("srn") String srn) {
try {
List<BookMarkMRPostProcessCalc> calcList = bookMarkMrPostProcessCalcService.getPostProcessCalc(srn);
return ResponseUtil.prepareRestResponse(calcList);
} catch (BookMarkServiceException e) {
return ResponseUtil.prepareErrorRestResponse(e.getMessage(), "", e.toString());
}
}
The positive scenario works fine. I want to write test cases for the scenario when BookMarkServiceException
occurs or mock it. How can we achieve this in junit?
One way of doing it is as below:
@RunWith(SpringRunner.class)
public class YourClassNameTest {
@InjectMocks
pricvate YourClassName yourClassName;
@Rule
public ExpectedException exceptionRule = ExpectedException.none();
@Test
public void fetchLatestPostProcessCalcTest(){
expectedException.expect(BookMarkServiceException.class);
yourClassName.fetchLatestPostProcessCalc("input that would generate error");
}