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

car*_*ing 6 java junit spring

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

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

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

Grz*_*icz 4

第一个解决方案

请改用TestNG
@Before*注释在 TestNG 中的行为方式如下
注释的方法不必@Before*是静态的。

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

第二种解决方案

如果您不想这样做,您可以使用Spring ( )中的执行侦听器AbstractTestExecutionListener

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

@TestExecutionListeners({CustomTestExecutionListener.class})
public class Test {
    //Some methods with @Test annotation.
}
Run Code Online (Sandbox Code Playgroud)

然后CustomTestExecutionListener用这个方法来实现:

public void beforeTestClass(TestContext testContext) throws Exception {
    //Your before goes here.
}
Run Code Online (Sandbox Code Playgroud)

独立于一个文件中,如下所示:

@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.");
    }
}
Run Code Online (Sandbox Code Playgroud)