6.3 Contributing OSGi sourced dependencies

In the previous step the JpaDirectorySpringContextTests test failed because it did not have a DataSource to be injected. In this step, you will instantiate an “in-process” database for testing and populate it with data.

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

Proceed to the next step.