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

时间:2011-03-04 10:31:18

标签: java spring maven testng spring-test

我在依赖注入(Spring autowiring)和maven-surefire方面遇到了一些问题。 使用TestNG在eclipse中运行时,以下测试没有问题: 注入service-object,然后调用@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);
}

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

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

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

行家-万无一失-插件:2.7.2

Eclipse:Helios Service Release 1

jdk1.6.0_14

TestNG:5.14.10

5 个答案:

答案 0 :(得分:19)

此外,在修复this issue之前,如果按照之前的建议后仍然无法正常工作,或者您不希望在每个方法之前执行代码,那么请将以下代码添加到您的考试类:

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

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

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

答案 1 :(得分:12)

使用@BeforeMethod,而不是@BeforeTest

答案 2 :(得分:7)

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

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

答案 3 :(得分:1)

使用@PostConstruct而非@BeforeXXX

答案 4 :(得分:0)

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

相关问题