Spring-Autowiring happens after @BeforeClass when running test with maven-surefire

I have some problems with dependency injection (Spring autowiring) and maven-surefire. The following test works without problems when running in eclipse using TestNG: The service object is entered, then the @BeforeClass method is @BeforeClass .

 @TransactionConfiguration(defaultRollback=false) @ContextConfiguration(locations={"/testContext.xml"}) public class MyServiceTest extends AbstractTransactionalTestNGSpringContextTests { @Autowired private MyService service; @BeforeTest public void setup() { System.out.println("*********************"+service); Assert.assertNotNull(service); } 

However, when I run the same test test with maven-surefire, the first setup () is called, which causes the test to fail:

 [INFO] --- maven-surefire-plugin:2.7.2:test (default-test) @ myserver --- [INFO] Surefire report directory: D:\... ------------------------------------------------------- TESTS ------------------------------------------------------- Running TestSuite **************************null 2011-03-04 11:08:57,462 DEBUG ionTestExecutionListener.prepareTestInstance - Performing dependency injection for test context [[TestContext@1fd6bea... 2011-03-04 11:08:57,462 DEBUG ractGenericContextLoader.loadContext - Loading ApplicationContext for locations [classpath:/testContext.xml]. 

How can I solve this problem? If I replaced @BeforeClass with @Test , it will work in maven, as in the TestNG eclipse plugin.

Maven-error-free plugin: 2.7.2

Eclipse: Helios Service Release 1

jdk1.6.0_14

TestNG: 5.14.10

+19
java spring spring-test maven testng
Mar 04 2018-11-11T00:
source share
5 answers

In addition, until this problem is fixed, if it still does not work for you after following the previous tip OR you do not want your code to be executed before each separate method, then add the following code to the test class:

 @Override @BeforeSuite protected void springTestContextPrepareTestInstance() throws Exception { super.springTestContextPrepareTestInstance(); } 

This ensures that the Spring context is prepared before your @BeforeClass methods are executed.

* Notice, I posted this answer as you are asking about @BeforeClass in the header, although @BeforeClass is not used in your code example.

+18
May 08 '11 at 18:00
source share

Use @BeforeMethod , not @BeforeTest .

+12
Mar 04 2018-11-17T00:
source share

I agree with Cedric: use @BeforeMethod instead of @BeforeTest , since Spring dependency injection takes place in the @BeforeClass method.

  • Sam (author of Spring TestContext Framework;))
+7
Mar 09 '11 at 17:31
source share

Use @PostConstruct not @BeforeXXX

+1
Mar 04 '14 at 11:21
source share

Check if you have spring -asm dependency. If you have one, it will conflict with the spring -core dependency. I removed the asm dependency and it worked for me.

0
Apr 21 '15 at 21:35
source share



All Articles