使用TestNG进行Spring依赖注入

Phư*_*yễn 54 junit testng spring

Spring支持JUnit:使用RunWithContextConfiguration注释,事情看起来非常直观

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:dao-context.xml")
Run Code Online (Sandbox Code Playgroud)

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

lex*_*ore 56

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

  • 真是一团糟.首先强制执行特定的类层次结构.其次是非常混乱,因为使用`@Transactional`的测试用例可能会错误地扩展非事务性版本.但不幸的是,没有其他方法可以将Spring与TestNG一起使用. (6认同)

Aru*_*kar 26

这是一个适合我的例子:

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!
    }
}
Run Code Online (Sandbox Code Playgroud)


rom*_*ara 18

Spring和TestNG很好地协同工作,但有一些事情需要注意.除了继承AbstractTestNGSpringContextTests之外,您还需要了解它与标准TestNG设置/拆卸注释的交互方式.

TestNG有四个级别的设置

  • BeforeSuite
  • BeforeTest
  • 课前
  • BeforeMethod

它完全按照您的预期发生(自我文档API的很好的例子).这些都有一个名为"dependsOnMethods"的可选值,它可以使用String或String [],它是同一级别的方法的名称或名称.

AbstractTestNGSpringContextTests类有一个名为springTestContextPrepareTestInstance的BeforeClass注释方法,您必须将其设置为依赖于是否在其中使用自动装配的类.对于方法,您不必担心自动装配,因为它是在类之前的方法中设置测试类时发生的.

这就留下了如何在使用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!
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 不幸的是,这对我不起作用.默认情况下,@ @ Autowire`似乎在@BeforeTest(但在@Test之前)之后很晚才发生.我尝试添加dependsOnMethods,但后来得到:MyClass依赖于方法protected void org.springframework.test.context.testng.AbstractTestNGSpringContextTests.springTestContextPrepareTestInstance()抛出java.lang.Exception,它没有用@Test注释... (2认同)