62

Spring 对 JUnit 的支持非常好:使用RunWithandContextConfiguration注释,事情看起来很直观

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

该测试将能够在 Eclipse 和 Maven 中正确运行。我想知道TestNG是否有类似的东西。我正在考虑转向这个“下一代”框架,但我没有找到与 Spring 进行测试的匹配项。

4

3 回答 3

62

它也适用于 TestNG。您的测试类需要扩展以下类之一:

于 2010-04-09T15:14:03.017 回答
30

这是一个对我有用的例子:

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!
    }
}
于 2012-04-02T16:59:00.440 回答
22

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!
    }
}
于 2013-05-10T02:55:12.360 回答