小编use*_*434的帖子

MockMVC将测试控制器与会话范围的Bean集成

我正在尝试集成测试使用注入到控制器的spring session作用域bean的Spring Controller方法。为了使测试通过,我必须能够访问我的会话bean,以便在对该控制器方法进行模拟调用之前为其设置一些值。问题是当我进行调用而不是使用我从模拟应用程序上下文中拉出的那个时创建了一个新的会话bean。如何使我的控制器使用相同的UserSession bean?

这是我的测试用例

    @RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration("src/main/webapp")
@ContextConfiguration({"file:src/main/webapp/WEB-INF/applicationContext.xml",
        "file:src/main/webapp/WEB-INF/rest-servlet.xml",
        "file:src/main/webapp/WEB-INF/servlet-context.xml"})
public class RoleControllerIntegrationTest {

    @Autowired
    private WebApplicationContext wac;

    protected MockMvc mockMvc;
    protected MockHttpSession mockSession;

    @BeforeClass
    public static void setupClass(){
        System.setProperty("runtime.environment","TEST");
        System.setProperty("com.example.UseSharedLocal","true");
        System.setProperty("com.example.OverridePath","src\\test\\resources\\properties");
        System.setProperty("JBHSECUREDIR","C:\\ProgramData\\JBHSecure");
    }

    @Before
    public void setup(){
        mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
        mockSession = new MockHttpSession(wac.getServletContext(), UUID.randomUUID().toString());
        mockSession.setAttribute("jbhSecurityUserId", "TESTUSER");
    }

    @Test
    public void testSaveUserRole() throws Exception {

        UserSession userSession = wac.getBean(UserSession.class);
        userSession.setUserType(UserType.EMPLOYEE);
        userSession.setAuthorizationLevel(3);

        Role saveRole = RoleBuilder.buildDefaultRole();
        Gson gson = new Gson();
        String json = gson.toJson(saveRole);

        MvcResult result = this.mockMvc.perform(
                post("/role/save") …
Run Code Online (Sandbox Code Playgroud)

junit integration-testing spring-mvc stateful-session-bean mockmvc

6
推荐指数
1
解决办法
2315
查看次数