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

会有一股神秘感。 提交于 2019-12-20 09:36:02

问题


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

@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 very same testcase with maven-surefire, 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:\...
-------------------------------------------------------
 T E S T S
-------------------------------------------------------
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 replace @BeforeClass with @Test it works in maven as in TestNG's eclipse plugin.

maven-surefire-plugin:2.7.2

Eclipse: Helios Service Release 1

jdk1.6.0_14

TestNG: 5.14.10


回答1:


Additionally, until this issue is fixed, if things still aren't working for you after following the previous advice OR you do not wish your code to be executed before every single method, then add the following code to your test class:

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

This ensures that the Spring Context will be prepared before your @BeforeClass methods are executed.

*note, I posted this answer since in the title you're asking about @BeforeClass, even though there is no usage of @BeforeClass in your sample code.




回答2:


Use @BeforeMethod, not @BeforeTest.




回答3:


I agree with Cedric: use @BeforeMethod instead of @BeforeTest, since Spring's dependency injection occurs in an @BeforeClass method.

  • Sam (author of the Spring TestContext Framework ;) )



回答4:


Use @PostConstruct not @BeforeXXX




回答5:


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



来源:https://stackoverflow.com/questions/5192562/spring-autowiring-happens-after-beforeclass-when-running-test-with-maven-surefi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!