使用maven-surefire运行测试时,在@BeforeClass之后发生Spring-Autowiring

我在dependency injection(Spring autowiring)和maven-surefire方面遇到了一些问题。 以下测试在使用TestNG在eclipse中运行时没有问题:注入service-object,然后调用@BeforeClass -method。

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

但是,当我使用maven-surefire运行相同的测试用例时,首先调用setup(),这会导致测试失败:

 [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]. 

我怎么解决这个问题? 如果我用@Test替换@BeforeClass ,它就像在TestNG的eclipse插件中一样在maven中工作。

Maven的万无一失,插件:2.7.2

Eclipse:Helios Service Release 1

jdk1.6.0_14

TestNG:5.14.10

此外,在修复此问题之前,如果在遵循先前的建议后仍然无法正常工作,或者您不希望在每个方法之前执行代码,则将以下代码添加到测试类中:

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

这确保了在执行@BeforeClass方法之前准备Spring Context。

*注意,我发布了这个答案,因为在您询问@BeforeClass的标题中,即使您的示例代码中没有使用@BeforeClass。

使用@BeforeMethod ,而不是@BeforeTest

我同意Cedric:使用@BeforeMethod代替@BeforeTest ,因为Spring的dependency injection发生在@BeforeClass方法中。

  • Sam(Spring TestContext Framework的作者;))

使用@PostConstruct而不是@BeforeXXX

检查你是否也有spring-asm依赖。 如果你有一个它将与spring-core依赖冲突。 我删除了asm依赖项,这对我有用。