6. Testing GreenPages

Testing is one of the most important aspects of software development. Without testing it would be difficult to determine if a piece of code worked properly, changes would have undetected consequences, and the quality of products would generally be lower.

There are two major categories of testing generally recognised today: unit testing and integration testing. In the context of the GreenPages application, unit testing means testing a single class in isolation from other application code. This type of testing does not change at all when developing for dm Server.

In our application integration testing means testing an application or portion of an application with other code. This kind of testing does look a bit different when developing for dm Server. In most cases dm Server applications are made up of small bundles that consume services through the OSGi registry. In the following steps a single bundle and the entire GreenPages application will be integration tested outside the container.

6.1 Single bundle integration testing

One of the most common forms of integration testing is ensuring that the object relational mapping in an application is working properly. This kind of testing typically uses a data access object to retrieve data from a live database. In this step a test case for the JpaDirectory class is created.

Open the greenpages.jpa.JpaDirectorySpringContextTests class in the src/test/java source folder of the greenpages.jpa project. This class contains a method that uses JUnit to test that a search completes correctly. Rather than instantiate this class directly in the test, the Spring Test Framework is used to instantiate and inject a JpaDirectory based on the META-INF/spring/module-context.xml file.

Add Spring Test Framework declarations to the test class. These declarations run the test with the SpringJunit4ClassRunner and configure the test with the classpath:/META-INF/spring/module-context.xml file:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:/META-INF/spring/module-context.xml")
@TestExecutionListeners(value = DependencyInjectionTestExecutionListener.class)
public class JpaDirectorySpringContextTests {
…

Use Eclipse to suggest the necessary imports until there are no errors.

When this configuration is complete, click on the Run drop-down menu and select Run Configurations…. In the the dialog that opens select JUnitJpaDirectorySpringContextTests and press Run.

This test run will fail because there is no DataSource bean to be injected; it is typically sourced from the OSGi service registry at runtime:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: 
    No bean named 'dataSource' is defined

The next step will correct this error.