我是JUnit测试的新手,我在为if / else语句编写一个时遇到问题。我写了一个简单的JUnit测试,但它跳过所有if else语句(我需要检查url传递以进行检查)并转到最后一个else语句。我相信这里的问题是url本身没有被检查。我如何在JUnit中测试其余的if / else语句(首先是if / else是否已经过测试)。我正在添加我的java类和Junit测试。
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");
}
答案 0 :(得分:1)
你应该在另一个junit测试中修改你的模拟when
when(req.getRequestURI()).thenReturn("url/url/url/url/url/url/url/url");
并尽可能多地使用junits以便正确测试