tho*_*oer 21 java testng spring spring-test maven
我在依赖注入(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);
}
Run Code Online (Sandbox Code Playgroud)
但是,当我使用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].
Run Code Online (Sandbox Code Playgroud)
我怎么解决这个问题?如果我更换@BeforeClass
与@Test
它在行家的作品作为TestNG的Eclipse插件.
Maven的万无一失,插件:2.7.2
Eclipse:Helios Service Release 1
jdk1.6.0_14
TestNG:5.14.10
Aid*_*n O 21
此外,在修复此问题之前,如果在遵循先前的建议后仍然无法正常工作,或者您不希望在每个方法之前执行代码,则将以下代码添加到测试类中:
@Override
@BeforeSuite
protected void springTestContextPrepareTestInstance() throws Exception {
super.springTestContextPrepareTestInstance();
}
Run Code Online (Sandbox Code Playgroud)
这确保了在执行@BeforeClass方法之前准备Spring Context.
*注意,我在@BeforeClass的标题中发布了这个答案,即使你的示例代码中没有使用@BeforeClass.
我同意Cedric:使用@BeforeMethod
而不是@BeforeTest
,因为Spring的依赖注入发生在@BeforeClass方法中.