junit MockMVC将测试控制器与会话作用域bean集成

0h4hbjxa  于 2023-08-05  发布在  其他
关注(0)|答案(3)|浏览(104)

我正在尝试集成测试一个Spring控制器方法,该方法使用一个注入到控制器中的Spring会话作用域bean。为了让我的测试通过,我必须能够访问我的会话bean,在对这个控制器方法进行模拟调用之前在它上面设置一些值。问题是,当我进行调用时,创建了一个新的会话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")
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(json)
                        .session(mockSession))
                .andExpect(status().isOk())
                .andReturn();

        MockHttpServletResponse response = result.getResponse();

    }

字符串
这里是我的控制器的方法,我需要测试

@Resource(name="userSession")
    private UserSession userSession;

    @RequestMapping(method = RequestMethod.POST, value = "/save")
    public @ResponseBody ServiceResponse<Role> saveRole(@RequestBody Role role,HttpSession session){

        if(userSession.isEmployee() && userSession.getAuthorizationLevel() >= 3){
            try {
                RoleDTO savedRole = roleService.saveRole(role,ComFunc.getUserId(session));
                CompanyDTO company = userSession.getCurrentCompany();


它不传递此行,因为UserSession对象与if(userSession.isEmployee()&& userSession.getAuthorizationLevel()>= 3){
这是我的用户会话bean的声明。

@Component("userSession")
   @Scope(value="session",proxyMode= ScopedProxyMode.INTERFACES)
   public class UserSessionImpl implements UserSession, Serializable  {

    private static final long serialVersionUID = 1L;


controlle和bean都是使用applicationContext.xml中的组件扫描创建的

<context:annotation-config />
    <!-- Activates various annotations to be detected in bean classes -->
    <context:component-scan
        base-package="
            com.example.app.externalusersecurity.bean,
            com.example.app.externalusersecurity.service,
            com.example.app.externalusersecurity.wsc"/>
    <mvc:annotation-driven />

mbzjlibv

mbzjlibv1#

添加下面的bean配置,它为每个线程添加一个会话上下文

<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
    <property name="scopes">
        <map>
            <entry key="session">
                <bean class="org.springframework.context.support.SimpleThreadScope"/>
            </entry>
        </map>
    </property>
</bean>

字符串
Java的配置类中的一个等价物是下面的bean声明

@Bean
  public CustomScopeConfigurer scopeConfigurer() {
    CustomScopeConfigurer configurer = new CustomScopeConfigurer();
    Map<String, Object> workflowScope = new HashMap<String, Object>();
    workflowScope.put("session", new SimpleThreadScope());
    configurer.setScopes(workflowScope);

    return configurer;
  }


有关更多详细信息,请访问http://docs.spring.io/spring/docs/4.0.x/spring-framework-reference/html/beans.html#beans-factory-scopes-custom-using

jtw3ybtb

jtw3ybtb2#

使用不同的Bean定义配置文件进行测试和生产对我来说很有效--下面是基于XML的设置的样子:

<beans profile="production">
    <bean id="userSession" class="UserSessionImpl" scope="session" >
        <aop:scoped-proxy/>
    </bean>
</beans>

<beans profile="test">
    <bean id="userSession" class="UserSessionImpl" >
    </bean>
</beans>

字符串
要在测试中使用测试配置文件,请将@ActiveProfiles添加到测试类中:

@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"})
@ActiveProfiles(profiles = {"test"})
public class RoleControllerIntegrationTest {
[...]

kmb7vmvb

kmb7vmvb3#

有点情境的情况下,如果有人会使用@WebMvcTest进行测试,那么你也可以手动触发会话范围的启动,就像Sping Boot 在Junit 5中做的那样:

@ActiveProfiles(profiles = {"TEST"})
@WebMvcTest
@ContextConfiguration(classes = {ApplicationConfiguration.class})
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class MvcTest{

@Autowired
protected MockMvc mockMvc;

@BeforeAll
public void activateSessionScope() {
    ConfigurableListableBeanFactory clbf = ((AbstractApplicationContext) mockMvc.getDispatcherServlet().getWebApplicationContext()).getBeanFactory();
    WebApplicationContextUtils.registerWebApplicationScopes(clbf, mockMvc.getDispatcherServlet().getServletContext());
}

字符串
这将导致您的会话范围真正绑定到会话,并且您可以使用MockHttpSession操作Session bean值。

相关问题