0

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");
}
4

1 回答 1

1

你应该when在另一个junit测试中修改你的嘲笑

when(req.getRequestURI()).thenReturn("url/url/url/url/url/url/url/url");

并制作尽可能多的junit以便正确测试它

于 2013-10-18T10:06:08.480 回答