我们如何在JUnit中模拟会话值(request.getSession())? [英] How can we mock session values (request.getSession() ) in JUnit?
本文介绍了我们如何在JUnit中模拟会话值(request.getSession())?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
private BankApp processSelection(HttpServletRequest request,
String[] facets, String selectedText) {
DebugUtility.debug(LOG, "Enter into JiraController :: processDashBoardPortFolioSelection()");
BankApp project = new BankApp();
List<BankApp> dataAgg = (List<BankApp>) request.getSession()
.getAttribute(PROJECT_WISE_SESSION);
if (CollectionUtils.isNotEmpty(dataAgg)) {
List<BankApp> projects = new ArrayList<>();
for (String currentProjectId : facets) {
Project currProject = vendorUtils.getProjectDetails(currentProjectId);
List<SourceProjectAssocation> sourceSystem = currProject.getSourceSytems("JIRA");
List<String> jiraProjects = new ArrayList<>();
sourceSystem.stream().forEach(s -> jiraProjects.add(s.getAssociatedJiraProject()));
for (BankApp projectData : dataAgg) {
if (jiraProjects.contains(projectData.getProjectKey())) {
projects.add(projectData);
}
}
}
project = processAllProjectsData(projects);
project.setProjectKey(selectedText);
project.setProjectsCount(projects.size());
}
DebugUtility.debug(LOG, "project in processDashBoardPortFolioSelection :: " + project);
DebugUtility.debug(LOG, "Exit from JiraController :: processDashBoardPortFolioSelection()");
return project;
}
如何为该方法编写junit测试用例?我在这里面临的挑战是我们需要模拟request.getSession().getAttribute(PROJECT_WISE_SESSION)
.所以我尝试了when(request.getSession()).thenReturn(session);
,但是使用request.getSession()
我得到了null
.
How can we write junit test case for this method? The challenge I'm facing here is we need to mock request.getSession().getAttribute(PROJECT_WISE_SESSION)
. So I tried when(request.getSession()).thenReturn(session);
but with request.getSession()
I'm getting null
.
推荐答案
尝试类似的方法
@Test
public void test() {
HttpServletRequest requestMock = Mockito.mock(HttpServletRequest.class);
HttpSession sessionMock = Mockito.mock(HttpServletRequest.class);
Mockito.when(requestMock.getSession()).thenReturn(sessionMock);
processSelection(requestMock, <and your facets and selectedText here>)
//do some asserts/verifies here
}
这篇关于我们如何在JUnit中模拟会话值(request.getSession())?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文