我正在尝试使用dbunit来测试系统的数据库。由于可以使用相同的数据集测试多个测试用例,因此我想为所有测试用例初始化一次数据集。但我也使用spring的@AutoWire来初始化那些数据库连接参数。
我尝试使用@BeforeClass和@AfterClass来设置数据库。但事实证明 @Autowire 在类启动时发生(似乎不适用于自动连接静态成员)。
所以想知道是否有其他方法可以在所有测试用例之前/之后设置/拆除数据库数据集?
我找到了一个优雅的解决方案:
How to allow instance methods to run as JUnit BeforeClass behavior
这篇文章基本上解释了一种更改单元测试运行程序以触发事件的方法。 对于 spring,也可以使用 AbstractTestExecutionListener
最佳答案
只需使用ApplicationListener接口(interface)初始化数据库即可。请看一下这个问题: How to add a hook to the application context initialization event?可以在 onApplicationEvent 方法中创建所有数据。
无论如何,不要使用 dbunit,只需使用 @Transactional 和 @DirtiesContext 创建所有测试即可。 (类级别的 DirtiesContext)使用 ClassMode=AfterEachTestMethod 所以代码会是这样的:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "classpath:testContext.xml" })
@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
public class YourTestClassTest {
//...
}
关于java - 如何在不使用静态 @BeforeClass 的情况下设置/拆卸 dbunit 数据集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26794313/