2014-10-27 100 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

相關問題