Reputation: 47
please could someone help me with following problem. Is there any way how to load database from sql datafile? In my tests i am using dbunit. I just normally create new databse schema on my local mysql server and then load all data to this schema and then just testing it in java just like this
@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);
}
}
but i need to load database from sql file before each test, i mean that i want to load database from sql file into empty database schema. In dbunit there is something like @DatabaseSetup("test_db.sql"), but this isn't for sql file i think. Please, is there any way how to do it?
Upvotes: 1
Views: 3918
Reputation: 12688
I perfer to executing SQL scripts declaratively with @Sql.
@Sql("/test_db.sql")
@Transactional
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:context/DAOTestContext.xml")
public class HistoricalDataDAOTest {
...
}
I would also suggest using @Transactional in your test. This will cause any changes to your db to be rollback. It can be applied at either the class or method level.
The chapter in the manual about this - https://docs.spring.io/spring/docs/current/spring-framework-reference/html/integration-testing.html#testcontext-executing-sql
Upvotes: 2
Reputation: 434
Since you are using Spring, you can use ScriptUtils in your @Before method:
Connection connection = dataSource.getConnection();
ScriptUtils.executeSqlScript(connection, new ClassPathResource("test_db.sql"));
Upvotes: 4