java - jUnit if/else 语句 java

标签 java if-statement junit mockito

我是 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/

相关文章:

java - 我不断从方法中得到零

Java 单元测试 - 常量字段与 setUp()

java - MongoDB 相当于 WHERE IN(1,2,...)

java - 新的affectiva SDK ver 3.1.2使用难度

c - 在 C 中解释 "if (result1) *result1 = t2"语句时遇到问题

java - JUnit 与 TestNG

junit - Thucydides - @Step 中的断言失败后测试继续

java switch语句很多情况都简化了

java - 使用普通 JAVA Stream 收集 int 数组的值

vba - 使用 sum if 和两个不同的参数