java - 如何将@Before/@BeforeClass 与@Autowired 字段一起使用

标签 java spring junit

我有一个测试用例,它有一个 @Autowired 字段。我想要一种设置测试用例的方法,因为它有许多 @Test 注释方法,这些方法将依赖于相同的生成数据(为此我需要 Autowiring 类)。

实现此目标的好方法是什么?

如果我有 @BeforeClass,那么我需要将方法设为静态,这会破坏 Autowiring 。

最佳答案

第一个解决方案

使用TestNG相反。
@Before* 注释行为 this way在 TestNG 中。
@Before* 注释的方法都不必是静态的。

@org.testng.annotations.BeforeClass
public void setUpOnce() {
   //I'm not static!
}

第二种解决方案

如果你不想这样做,你可以使用 an execution listener from Spring (AbstractTestExecutionListener)。

您必须像这样注释您的测试类:

@TestExecutionListeners({CustomTestExecutionListener.class})
public class Test {
    //Some methods with @Test annotation.
}

然后用这个方法实现CustomTestExecutionListener:

public void beforeTestClass(TestContext testContext) throws Exception {
    //Your before goes here.
}

自包含在一个文件中,看起来像:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"commonContext.xml" })
@TestExecutionListeners({SimpleTest.class})
public class SimpleTest extends AbstractTestExecutionListener {

    @Override
    public void beforeTestClass(TestContext testContext) {
        System.out.println("In beforeTestClass.");
    }

    @Test
    public void test() {
        System.out.println("In test.");
    }
}

关于java - 如何将@Before/@BeforeClass 与@Autowired 字段一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42319851/

相关文章:

java - 单元测试由@Around 建议建议的方法

spring - 如何在 Spring Boot 的 application.yml 中配置滚动文件附加程序

当我尝试向客户添加另一个产品时发生 java.lang.StackOverflowError

java - 以编程方式加载 Spring 属性文件

java - 在 Junit4 (PowerMock) 中实现 Mocking 时的依赖关系

java - 从 Eclipse 中的多个项目运行 JUnit 测试

java - jar文件中的声音问题

java - 如何在java中将日期转换为十六进制

java - JNI加载类问题

java - DBUnit 的奇怪 DB2 问题