【问题标题】:How to make @BeforeClass run prior Spring TestContext loads up?如何让 @BeforeClass 在 Spring TestContext 加载之前运行?
【发布时间】:2011-01-03 22:35:06
【问题描述】:

对于使用 testNG 的程序员来说,这应该是小菜一碟。我有这种情况

    @ContextConfiguration(locations={"customer-form-portlet.xml", "classpath:META-INF2/base-spring.xml" })
    public class BaseTestCase extends AbstractTestNGSpringContextTests {

...
        @BeforeClass
        public void setUpClass() throws Exception {

但我需要在 @BeforeClass 之后加载 spring 上下文。我想出了重写 AbstractTestNGSpringContextTests 方法:

@BeforeClass(alwaysRun = true)
protected void springTestContextBeforeTestClass() throws Exception {
    this.testContextManager.beforeTestClass();
}

@BeforeClass(alwaysRun = true, dependsOnMethods = "springTestContextBeforeTestClass")
protected void springTestContextPrepareTestInstance() throws Exception {
    this.testContextManager.prepareTestInstance(this);
}

做我的方法

@BeforeClass(alwaysRun = true, dependsOnMethods = "setUpClass")
protected void springTestContextPrepareTestClass() throws Exception {
}

但后来我明白了:

原因:org.testng.TestNGException: org.springframework.test.context.testng.AbstractTestNGSpringContextTests.springTestContextPrepareTestInstance() 不允许依赖于受保护的 空白 org.springframework.test.context.testng.AbstractTestNGSpringContextTests.springTestContextBeforeTestClass() 抛出 java.lang.Exception

公开也无济于事。可以请任何人在此处提及是否可以以工作方式完成 :-) 我知道我可以手动加载 testContext,但这不会那么花哨。

它是这样工作的,但是 TestContextManager 是不可见的,所以我不能在它上面调用 prepareTestInstance() 方法:

@Override
@BeforeClass(alwaysRun = true, dependsOnMethods = "setUpClass")
public void springTestContextPrepareTestInstance() throws Exception {
}

【问题讨论】:

    标签: java spring junit testng spring-test


    【解决方案1】:

    我创建了自定义的 DependencyInjectionTestExecutionListener 并且我已经覆盖了 injectDependencies() 方法并在那里完成了我的初始化代码

    @TestExecutionListeners( inheritListeners = false, listeners = {DITestExecutionListener.class, DirtiesContextTestExecutionListener.class})
    @ContextConfiguration(locations= "customer-form-portlet.xml")
    public class BaseTestCase extends AbstractTestNGSpringContextTests {
    

    public class DITestExecutionListener extends DependencyInjectionTestExecutionListener {
    
    
        protected void injectDependencies(final TestContext testContext) throws Exception {
    
            INITSTUFF();
    
            Object bean = testContext.getTestInstance();
            AutowireCapableBeanFactory beanFactory = testContext.getApplicationContext().getAutowireCapableBeanFactory();
            beanFactory.autowireBeanProperties(bean, AutowireCapableBeanFactory.AUTOWIRE_NO, false);
            beanFactory.initializeBean(bean, testContext.getTestClass().getName());
            testContext.removeAttribute(REINJECT_DEPENDENCIES_ATTRIBUTE);
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-02
      相关资源
      最近更新 更多