我有大约 10 个将自动执行的 JUnit。我想重置每个数据库中的数据库。我有这段代码:
//@Transactional
public class TestMediaObjectService extends AbstractDataAccessTest{
//This method reset the database, emptying the tables
@Test
public void testCreateDataBase() throws Exception {
TestDatabaseCreation creation = new TestDatabaseCreation();
creation.resetDatabase();
}
//This is one of the methods.
@Test
public void testStoreMediaObject() throws Exception {
//......
}
当我使用我在方法 testCreateDataBase
中使用的相同脚本手动重置数据库,然后运行此测试(没有该方法)时,表会自动创建。但是,如果我按照上面粘贴的方式运行代码,则不会创建该表,因此我会收到此错误:
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'one_table' doesn't exist
在测试中运行其他方法之前,如何在 every 中运行该方法?注释 @Transactional
已删除,但错误仍然存在。
最佳答案
通常您不需要手动重置数据库,因为 JUNIT 会在每次测试前为您完成此操作。使用这些注释:
@TransactionConfiguration(defaultRollback = true)
@Transactional
@RunWith(SpringJUnit4ClassRunner.class)
Junit 将在运行后回滚测试中完成的所有事务。您只需要一个现有的空数据库。如果你使用 hibernate 来管理你的实体,你甚至不需要有表。
如果您想手动执行此操作,请在设置方法中使用 @Before
注释:
@Before
public void init() {
createTables();
}
这将在每次测试之前运行。
如果您想为一个类中的所有测试设置一次数据库表,请使用@BeforeClass
。但通常这不是最佳实践,因为每个测试都应该独立于任何其他测试。
关于mysql - 在运行 JUnit 测试之前重置 mysql 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8891369/