使用Mockito.when(wctx.getHttpServletRequest()).thenReturn(request);
请建议任何解决方案。
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");
}