Java 在每次测试之前加载SQL数据库

Java 在每次测试之前加载SQL数据库,java,mysql,junit4,spring-test,Java,Mysql,Junit4,Spring Test,请有人帮我解决以下问题。有没有办法从sql数据文件加载数据库?在我的测试中,我使用dbunit。我通常只是在本地mysql服务器上创建新的数据库模式,然后将所有数据加载到此模式,然后像这样在java中测试它 @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:context/DAOTestContext.xml") public class HistoricalDataDAOTe

请有人帮我解决以下问题。有没有办法从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);
}

}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations=“classpath:context/DAOTestContext.xml”)
公共类历史数据测试{
私有最终整数id=66124;
私有最终整数startDate=20140101;
私有最终整数endDate=20140102;
@自动连线
私有历史数据道histDataDAO;
公共历史数据测试(){
}
@课前
公共静态void setUpClass(){
}
@下课
公共静态void tearDownClass(){
}
@以前
公共作废设置(){
}
@之后
公共无效拆卸(){
}
@试验
公共无效getTest(){
列表部分=histDataDAO.get(“ing”、开始日期、结束日期);
系统输出打印项次(部分);
资产不为空(部分);
}
@试验
public void getByOrderIdTest(){
列表h=histDataDAO.getByOrderId(id);
assertNotNull(h);
}
}
但我需要在每次测试之前从sql文件加载数据库,我的意思是我想从sql文件加载数据库到空的数据库模式中。在dbunit中,有如下内容 @DatabaseSetup(“test_db.sql”),但我认为这不是用于sql文件的。
请问,有什么办法吗?

因为您使用的是Spring,所以可以在@Before方法中使用:

Connection connection = dataSource.getConnection();
ScriptUtils.executeSqlScript(connection, new ClassPathResource("test_db.sql"));

由于您使用的是Spring,因此可以在@Before方法中使用:

Connection connection = dataSource.getConnection();
ScriptUtils.executeSqlScript(connection, new ClassPathResource("test_db.sql"));
我宁愿去

我还建议在测试中使用@Transactional。这将导致回滚对数据库的任何更改。它可以应用于类或方法级别

手册中关于这一点的章节- 我喜欢

我还建议在测试中使用@Transactional。这将导致回滚对数据库的任何更改。它可以应用于类或方法级别

手册中关于这一点的章节-

您好,很抱歉回答了这么长时间。谢谢你的解决方案,它帮助我解决了部分问题。嗨,很抱歉回答了这么长时间。谢谢你的解决方案,它帮助我解决了部分问题。