请有人帮我解决以下问题。有什么方法可以从 sql 数据文件加载数据库吗?在我的测试中,我使用的是 dbunit。我通常只是在我的本地 mysql 服务器上创建新的数据库模式,然后将所有数据加载到这个模式,然后像这样在 java 中测试它
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:context/DAOTestContext.xml")
public class HistoricalDataDAOTest {
private final Integer id = 66124;
private final Integer startDate = 20140101;
private final Integer endDate = 20140102;
@Autowired
private HistoricalDataDAO histDataDAO;
public HistoricalDataDAOTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
@Test
public void getTest() {
List portions = histDataDAO.get("ing", startDate, endDate);
System.out.println(portions);
assertNotNull(portions);
}
@Test
public void getByOrderIdTest() {
List<HistoricalPortions> h = histDataDAO.getByOrderId(id);
assertNotNull(h);
}
}
但我需要在每次测试前从 sql 文件加载数据库,我的意思是我想将数据库从 sql 文件加载到空数据库模式中。在 dbunit 中有类似的东西 @DatabaseSetup("test_db.sql"),但我认为这不适用于 sql 文件。 请问有什么办法可以做到吗?
最佳答案
由于您使用的是 Spring,因此可以使用 ScriptUtils在你的@Before 方法中:
Connection connection = dataSource.getConnection();
ScriptUtils.executeSqlScript(connection, new ClassPathResource("test_db.sql"));
关于java - 每次测试前加载 SQL 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26582977/