How can we mock session values (request.getSession() ) in JUnit?

泄露秘密 提交于 2021-01-28 18:51:12

问题


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;
}

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.


回答1:


try something like that

@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
}


来源:https://stackoverflow.com/questions/58714540/how-can-we-mock-session-values-request-getsession-in-junit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!