春天和T estNG在一起工作得很好,但有些事情要注意。除了继承AbstractTestNGSpringContextTests之外,您还需要了解它如何与标准TestNG setup/teardown注释交互。
TestNG中有四个层次设置的
- BeforeSuite
- BeforeTest
- BeforeClass
- BeforeMethod
发生完全按照自己的预期(自文档的API很好的例子)。这些都有一个可选的值,名为“dependsOnMethods”,它可以接受一个String或String [],它是同级别方法的名称或名称。
AbstractTestNGSpringContextTests类有一个名为springTestContextPrepareTestInstance的BeforeClass批注方法,如果您在其中使用自动装配类,则必须将安装方法设置为依赖于它。对于方法,您不必担心自动装配,因为它是在类方法之前设置测试类时发生的。
这只是留下了如何在使用BeforeSuite注释的方法中使用自动装配类的问题。你可以通过手动调用springTestContextPrepareTestInstance来做到这一点 - 虽然它没有默认设置,但我已经成功完成了好几次。
所以,为了说明这一点,奥雅纳的例子的修改版本:
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!
}
}
感谢。这正是我要找的。 – 2010-04-10 03:20:36
真是一团糟。首先执行特定的类层次结构。其次,由于使用'@ Transactional'的测试用例可能错误地扩展了非事务版本,所以很令人困惑。但不幸的是,在TestNG中没有其他方法来使用Spring。 – 2014-10-22 09:53:44
@GrzesiekD。我希望在4.5年后有所改变。 :)所以请重新检查现状。 – lexicore 2014-10-22 09:55:21