i am new in JUnit test and i have a problem writing one for if/else statement. I wrote a simple JUnit test, but it skips all if else statements (where i need to check url passed for check) and goes to the last else statement. I believe a problem in here is url itself not being checked. How may i test the rest of if/else statements (first if/else is tested) in JUnit. I am adding my java class and Junit test.
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
JSONObject jsonObject = null;
int assetId = 0;
int journeyId = 0;
Date selectedDate = new Date();
selectedDate.setTime(selectedDate.getTime() - 30 * 1000 * 60 * 60 * 24);
String[] comps = req.getRequestURI().split("/");
if (comps.length == 6)
{
assetId = Integer.parseInt(comps[5]);
jsonObject = getJourneys(assetId, selectedDate);
resp.getWriter().write(jsonObject.toString(4));
}
else if (comps.length == 7)
{
assetId = Integer.parseInt(comps[5]);
journeyId = Integer.parseInt(comps[6]);
jsonObject = getAssetJourneys(assetId, journeyId);
resp.getWriter().write(jsonObject.toString(4));
}
else
{
resp.getWriter().write("Entered url is in wrong format, please check it and try again");
}
}
@Test
public void testUrl() throws Exception
{
GPSHistoryService gpsService = mock(GPSHistoryService.class);
HttpServletRequest req = mock(HttpServletRequest.class);
HttpServletResponse resp = mock(HttpServletResponse.class);
PrintWriter pw = mock(PrintWriter.class);
when(resp.getWriter()).thenReturn(pw);
when(req.getRequestURI()).thenReturn("url");
JourneyRestApiServlet jras = new JourneyRestApiServlet(gpsService);
jras.doGet(req, resp);
verify(pw).write("Entered url is in wrong format, please check it and try again");
}