如何创建模拟到Webcontext和webcontext工厂

时间:2015-10-23 17:28:56

标签: java mocking mockito webcontext

使用Mockito.when(wctx.getHttpServletRequest()).thenReturn(request);

进行模拟时,我收到NullPointerException

请建议任何解决方案。

Java类:

public String Sample(final String id, final String name) {
    returnString = "";
    final WebContext wctx = WebContextFactory.get();
    final HttpServletRequest request = wctx.getHttpServletRequest();
    Worker wrkDetail = WorkerDelegate.getWorker(id);

    try {
        if (wrkDetail == null) {
            request.setAttribute(ERROR_MESSAGE, CONSTANT_NO_DATA_FOUND_ERROR_MSG);
            returnString = CONSTANT_ERROR_DISPLAY;
        } else {
            final WrkrDetailAssoc assoc = new WrkrDetailAssoc();
            assoc.setFKId(wrkDetail.getId());
            getCurrentDetails(name, assoc);
        }
        String stdDetailsHtml = wctx.forwardToString("/StdDetail.htm");
        if (CONSTANT_NEW_LINE_CHAR.equals(stdDetailsHtml)) {
            stdDetailsHtml = CONSTANT_EMPTY_STRING;
        }
        returnString = stdDetailsHtml;
    }
    return returnString;
}

测试用例:

@Test
public void testGetWorkerDetails() throws Exception {
    MockHttpServletResponse response = new MockHttpServletResponse();
    MockHttpServletRequest request = new MockHttpServletRequest();
    DefaultWebContextBuilder builder = new DefaultWebContextBuilder();

    builder.set(request, response, null, null, null);

    WebContextFactory.setWebContextBuilder(builder);
    wctx = WebContextFactory.get();
    request = Mockito.mock(MockHttpServletRequest.class);
    request.addParameter("parameterName", "someValue");
    Mockito.when(wctx.getHttpServletRequest()).thenReturn(request);
    WrkrLeaveDetailAssoc assoc = new WrkrLeaveDetailAssoc();

    Sample("12345", "rad");
}

0 个答案:

没有答案