Как установить активный профиль пружины при тестировании Struts2
При тестировании автономной весенней среды мы можем сделать:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "classpath:spring-*.xml" })
@ActiveProfiles( profiles = { "Prod","bsi"})
public class SampleTest
При тестировании Struts 2 с пружинной интеграцией мы можем использовать:
public class SessionManagement extends StrutsSpringTestCase {
@Override
public String[] getContextLocations() {
return new String[] {"classpath:spring-*.xml"};
}
}
Но как я могу установить профиль активной пружины здесь?
1 ответ
Решение
Вы можете установить активные профили весной через контекстную среду приложения.
поскольку 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);
}
Юнит 4
Поскольку вы используете JUnit 4, есть StrutsSpringJUnit4TestCase
абстрактный класс. Расширьте его, и вы сможете использовать аннотации так же, как в SampleTest
,
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "classpath:spring-*.xml" })
@ActiveProfiles(profiles = { "Prod","bsi"})
public class SessionManagement extends StrutsSpringJUnit4TestCase<SomeAction>