对于使用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 {
}
答案 0 :(得分: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);
}