2010-04-09 113 views
43

Spring支持JUnit的很好的是: 随着RunWithContextConfiguration注释,事情看起来很直观春天依赖注入使用TestNG

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(locations = "classpath:dao-context.xml") 

本次测试将能够在Eclipse &的Maven在正常运行两者。 我不知道TestNG是否有类似的东西。我正在考虑转向这个“下一代”框架,但我没有找到与Spring进行测试的匹配。

回答

51
+0

感谢。这正是我要找的。 – 2010-04-10 03:20:36

+4

真是一团糟。首先执行特定的类层次结构。其次,由于使用'@ Transactional'的测试用例可能错误地扩展了非事务版本,所以很令人困惑。但不幸的是,在TestNG中没有其他方法来使用Spring。 – 2014-10-22 09:53:44

+0

@GrzesiekD。我希望在4.5年后有所改变。 :)所以请重新检查现状。 – lexicore 2014-10-22 09:55:21

23

这里是为我工作的例子:

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 { 

    public void testNullParamValidation() { 
     // Testing code goes here! 
    } 
} 
17

春天和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! 
    } 
} 
+0

方法org.springframework.test.context.testng。AbstractTestNGSpringContextTests#springTestContextPrepareTestInstance已经有注解@BeforeClass,所以这个解决方案在我看来是多余的。 – 2014-07-08 09:37:36

+1

该解决方案允许您将自动编译字段相关的代码添加到您的测试中。作为“before class”方法的“springTestContextPrepareTestInstance”并不保证它会在子类的“before class”之前运行 - 您需要明确设置dependsOnMethods字段 – romeara 2014-08-26 20:39:52

+2

不幸的是,这对我不起作用。默认情况下,@ Autowire似乎很晚才会在@BeforeTest(但在@Test之前)之后发生。我尝试添加dependsOnMethods,但后来我得到:MyClass取决于方法protected void org.springframework.test.context.testng.AbstractTestNGSpringContextTests.springTestContextPrepareTestInstance()抛出java.lang.Exception,它不用@Test注释... – dmansfield 2015-05-01 20:17:22