Spring 和 TestNG 可以很好地协同工作,但有一些事情需要注意。除了 subclassing 之外AbstractTestNGSpringContextTests
,您还需要了解它如何与标准 TestNG setup/teardown annotations 交互。
TestNG 有四个级别的设置
这完全符合您的预期(自记录 API 的绝佳示例)。这些都有一个可选值dependsOnMethods
,可以接受一个字符串或字符串[],这是同一级别的方法的名称或名称。
该类AbstractTestNGSpringContextTests
有一个BeforeClass
名为 的带注释的方法springTestContextPrepareTestInstance
,如果您在其中使用自动装配类,您必须将设置方法设置为依赖于该方法。对于方法,您不必担心自动装配,因为它发生在测试类设置在类之前的方法中时。
这只是留下了一个问题,即如何在使用 注释的方法中使用自动装配类BeforeSuite
。您可以通过手动调用来做到这一点springTestContextPrepareTestInstance
- 虽然默认情况下没有设置这样做,但我已经成功完成了几次。
因此,为了说明,Arup 示例的修改版本:
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.annotations.Test;
@Test
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class TestValidation extends AbstractTestNGSpringContextTests {
@Autowired
private IAutowiredService autowiredService;
@BeforeClass(dependsOnMethods={"springTestContextPrepareTestInstance"})
public void setupParamValidation(){
// Test class setup code with autowired classes goes here
}
@Test
public void testNullParamValidation() {
// Testing code goes here!
}
}