2011-01-03 6 views
4

これは、testNGを使用しているプログラマーのためのものです。私は、このシナリオSpring TestContextがロードされる前に@BeforeClassを実行する方法?

@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() は保護されていないことに依存することはできません 無効 org.springframework.test.context.testng.AbstractTestNGSpringContextTests.springTestContextBeforeTestClass() は役立ちません。また、それは公共の作りのjava.lang.Exception

をスローします。誰かがここに言及してくれればそれは実践的な方法で行うことができます:-)私は手動でtestContextを読み込むことができることを知っていますが、それはあまり面白くないでしょう。

それはこのように動作しますが、私はそれにprepareTestInstance()メソッドを呼び出すことはできませんのでTestContextManagerが表示されていない:

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

答えて

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); 
    } 
関連する問題