5

对于使用 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 之后加载弹簧上下文。II 提出了重写 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() 不允许依赖于受保护的 void org.springframework.test.context.testng.AbstractTestNGSpringContextTests.springTestContextBeforeTestClass() 抛出 java。语言异常

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

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

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

1 回答 1

2

好吧,我创建了自定义 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);
    }
于 2011-01-04T00:02:22.580 回答