【发布时间】:2018-03-09 21:34:22
【问题描述】:
我想知道是否可以通过TestRule 检索ApplicationContext。
这里TestRule 用于避免测试类之间的层次结构,其目的是重用基础设施配置但在这种情况下所需的结构是@ 987654324@ 已经由 Spring 创建。
为了简化共享代码,假设我们需要检索Environment 对象。
我尝试了这两种方法:
一个
@WebAppConfiguration
@ContextConfiguration(classes={RootApplicationContext.class, ServletApplicationContext.class})
public class ManolitoRule implements TestRule {
@Autowired
private Environment environment;
private static final Logger logger = LoggerFactory.getLogger(ManolitoRule.class.getSimpleName());
@Override
public Statement apply(Statement base, Description description) {
if(environment == null) {
logger.error("NULL");
}
else {
logger.info("Profiles: {}", Arrays.toString(environment.getActiveProfiles()));
}
return new Statement() {
//The @Before configuration should go here now
...
}
};
}
}
和
public class ManolitoTest {
private static final Logger logger = LoggerFactory.getLogger(ManolitoTest.class.getSimpleName());
@Rule
public ManolitoRule manolitoRule = new ManolitoRule();
@Test
public void manolitoTest() {
...
}
}
environment 是 null
两个
public class ManolitoRule implements TestRule {
private final Environment environment;
public ManolitoRule(Environment environment) {
this.environment = environment;
}
private static final Logger logger = LoggerFactory.getLogger(ManolitoRule.class.getSimpleName());
@Override
public Statement apply(Statement base, Description description) {
if(environment == null) {
logger.error("NULL");
}
else {
logger.info("Profiles: {}", Arrays.toString(environment.getActiveProfiles()));
}
return new Statement() {
//The @Before configuration should go here now
....
};
}
}
还有
@WebAppConfiguration
@ContextConfiguration(classes={RootApplicationContext.class, ServletApplicationContext.class})
@TestExecutionListeners(listeners={LoggingTestExecutionListener.class}, mergeMode=MergeMode.MERGE_WITH_DEFAULTS)
public class ManolitoTest {
private static final Logger logger = LoggerFactory.getLogger(ManolitoTest.class.getSimpleName());
@Autowired
private Environment environment;
@Rule
public ManolitoRule manolitoRule = new ManolitoRule(environment);
@Test
public void manolitoTest() {
...
}
}
environment 又是null
是否存在完成此配置的正确配置?
我的印象是JUnit 和Spring Framework 之间的生命周期是造成这种情况的原因。
注意:如果使用抽象类,一切正常。但考虑避免层次结构和链 @Rules 的场景,例如ManolitoRule 与SpringClassRule 和SpringMethodRule 一起工作
【问题讨论】:
标签: spring junit spring-test