如何在@Autowired字段中使用@ Before / @ BeforeClass

时间:2017-02-18 19:41:57

标签: java spring junit

我有一个具有@Autowired字段的测试用例。我想有一种方法来设置测试用例,因为它有许多@Test - 带注释的方法,它们将依赖于相同的生成数据(我需要自动化的类)。

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

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

2 个答案:

答案 0 :(得分:3)

第一个解决方案

请改用TestNG @Before*注释在TestNG中表现为this way 没有使用@Before*注释的方法必须是静态的。

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

第二个解决方案

如果您不想这样做,可以使用an execution listener from SpringAbstractTestExecutionListener)。

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

@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.");
    }
}

答案 1 :(得分:1)

我提出了创建一个用setUp注释的单独初始化方法(不是@PostConstruct)的解决方案。这不是一个优雅的解决方案,但它确保Spring在使用它们之前正确初始化了自动装配/注入的字段(这是静态@BeforeClass注释方法的初始问题)。