测试Struts2时如何设置spring active profile

时间:2016-02-03 07:34:20

标签: spring junit struts2 struts2-junit-plugin

在测试独立弹簧环境时,我们可以做到:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "classpath:spring-*.xml" })
@ActiveProfiles(  profiles = { "Prod","bsi"})
public class SampleTest 

使用spring集成测试Struts 2时,我们可以使用:

public class SessionManagement extends StrutsSpringTestCase  {

    @Override
    public String[] getContextLocations() {

      return new String[] {"classpath:spring-*.xml"};

    }
} 

但是如何在这里设置活动的弹簧轮廓?

1 个答案:

答案 0 :(得分:1)

您可以通过应用程序上下文环境在Spring中设置活动配置文件。

由于StrutsTestCase使用不可配置的GenericXmlContextLoader,您需要在测试中覆盖setupBeforeInitDispatcher方法并使用一些上下文(例如XmlWebApplicationContext),您可以在其中设置配置文件和致电refresh

@Override
protected void setupBeforeInitDispatcher() throws Exception {
    // only load beans from spring once
    if (applicationContext == null) {
        XmlWebApplicationContext webApplicationContext = new XmlWebApplicationContext();
        webApplicationContext.setConfigLocations(getContextLocations());
        webApplicationContext.getEnvironment().setActiveProfiles("Prod", "bsi");
        webApplicationContext.refresh();

        applicationContext = webApplicationContext;
    }

    servletContext.setAttribute(
            WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
            applicationContext);
}

JUnit 4

由于您正在使用JUnit 4,因此有StrutsSpringJUnit4TestCase个抽象类。扩展它,您可以像在SampleTest中一样使用注释。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "classpath:spring-*.xml" })
@ActiveProfiles(profiles = { "Prod","bsi"})
public class SessionManagement extends StrutsSpringJUnit4TestCase<SomeAction>