2014-10-27 94 views
0

请有人可以帮我解决以下问题。有没有办法如何从SQL数据文件加载数据库?在我的测试中,我使用了dbunit。我通常在我的本地MySQL服务器上创建新的DATABSE架构,然后所有的数据加载到这个模式,然后只是测试它在Java中就这样每次测试前加载SQL数据库

@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文件。 请问,有没有办法如何做到这一点?

回答

1

由于您使用Spring,你可以在你的@Before方法使用ScriptUtils

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

您好,对不起,很长一段时间来回答。感谢解决方案,它帮助我解决了我的部分问题。 – user1439198 2014-11-10 10:09:01

0

我perfer到executing SQL scripts declaratively with @Sql

@Sql("/test_db.sql") 
@Transactional 
@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(locations = "classpath:context/DAOTestContext.xml") 
public class HistoricalDataDAOTest { 
... 
} 

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

关于这个手册中的一章 - https://docs.spring.io/spring/docs/current/spring-framework-reference/html/integration-testing.html#testcontext-executing-sql

相关问题