How to make @BeforeClass launch before Spring TestContext loads?

this should be a piece of cake for programmers using testNG. I have this script

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

But I need a spring context to load after @BeforeClass. I came up with overriding the AbstractTestNGSpringContextTests methods:

 @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); } 

and make my method

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

But then I get:

Causes: org.testng.TestNGException: org.springframework.test.context.testng.AbstractTestNGSpringContextTests.springTestContextPrepareTestInstance () may not depend on invalid org.springframework.test.context.testng.AbstractTestNGSpringContextTests.springTestContextBeforeTestClass () throws java.lang.Exception

Making it public also does not help. Maybe someone will mention here if this can be done in working mode :-) I know that I can load testContext manually, but that would not be so interesting.

It works like this, but TestContextManager is not displayed, so I cannot call the prepareTestInstance () method on it:

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

Well, I created a custom DependencyInjectionTestExecutionListener, and I redefined the injectDependencies () method and made the initialization code there

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

and

 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); } 
+2
source

Source: https://habr.com/ru/post/1334134/


All Articles