gpt4 book ai didi

java - jUnit if/else 语句 java

转载 作者:行者123 更新时间:2023-12-01 13:59:08 25 4
gpt4 key购买 nike

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

最佳答案

您应该在另一个junit测试中修改您的模拟when

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

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

关于java - jUnit if/else 语句 java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19446879/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com