我有一个测试用例,它有一个 @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/