Building on Alfredos answer, this is a way to inject database information without calling the embedded database's default script. For instance, this may be useful when you want to automagically build the DDL for you - at least in tests.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"/applicationContext.xml"})
public class TestClass {
@Autowired
private ApplicationContext ctx;
private JdbcTemplate template;
@Autowired
public void setDataSource(DataSource dataSource) {
template = new JdbcTemplate(dataSource);
}
private static boolean isInitialized = false;
@Before
public void runOnce() {
if (isInitialized) return;
System.out.println("Initializing database");
String script = "classpath:script.sql";
Resource resource = ctx.getResource(script);
JdbcTestUtils.executeSqlScript(template, resource, true);
isInitialized = true;
}
}
This way, the runOnce()
method is called once and only once for the test run. If you make isInitialized
an instance field (non-static), the method will be called before every test. This way you can drop/repopulate the tables, if necessary, before every test run.
Note that this is still a rather quick-and-dirty solution and the sensible way to handle the database is in accordance with Ralph's answer.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…