In the previous step the JpaDirectorySpringContextTests test failed because it did
not have a DataSource to be injected. In this step, an
“in-process” database is instantiated and populated with data for testing.
Open the test-context.xml file in the
src/test/resources META-INF/spring folder.
In this file, define two beans; a
DataSource and a TestDataPopulator.
These two beans
will provide a test DataSource complete with test data.
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" p:driverClassName="org.h2.Driver" p:url="jdbc:h2:.~/greenpages-db/greenpages" p:username="greenpages" p:password="pass" init-method="createDataSource" destroy-method="close" /> <bean class="greenpages.jpa.TestDataPopulator" init-method="populate"> <constructor-arg ref="dataSource" /> <constructor-arg value="file:../../db/db.sql" /> </bean>
Open the JpaDirectorySpringContextTests class and update the
ContextConfiguration annotation to point at both the
module-context.xml file and the test-context.xml file:
@ContextConfiguration(locations = {
"classpath:/META-INF/spring/module-context.xml",
"classpath:/META-INF/spring/test-context.xml" })
Once again use the JpaDirectorySpringContextTests JUnit profile to run the test class.
Now that there is a DataSource being contributed, the test will pass.
If the test fails, check that the H2 database server is still running in the background.
Proceed to the next step.