Technology weblog

IT-Essence
Tuesday Feb 06, 2007

AbstractDependencyInjectionSpringContextTests

The AbstractDependencyInjectionSpringContextTests class provides

  • A mechanism that assures that the application context is only loaded once and reused for all subsequent unit tests
  • Automatic look-up of the class under test in the Spring config files that are made known to this by overriding the method
    protected abstract String[] getConfigLocations();
A typical application of this class is suggested below. We make a common base clase for all our unit tests:
/* $Id$ */

package my.package;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.AbstractDependencyInjectionSpringContextTests;

/**
* Base class for unit tests.
*
* @author Zeger Hendrikse.
* @version $Revision$
*
*/
public abstract class BaseTestCase extends AbstractDependencyInjectionSpringContextTests {

/** Test context. */
private static final String[] SPRING_JUNIT_CONTEXT = new String[] {
"spring-mock-context.xml",
"spring-context.xml",
"spring-another-context.xml"
};

/** Spring bean factory. */
protected ApplicationContext beanFactory = new ClassPathXmlApplicationContext(
SPRING_JUNIT_CONTEXT);

public BaseTestCase() {
super();
setAutowireMode(AUTOWIRE_BY_NAME);
}

protected String[] getConfigLocations() {
return SPRING_JUNIT_CONTEXT;
}

}
This class already implements the mandatory getConfigLocations() method. In addition, the Spring bean factory is made available to all test cases (subclassing from this base class), which might come in handy. Finally, note the configuration of the autowiring mode in the constructor of this base testcase. This makes Spring look up and instantiate a bean from the application context by the name of the member variable in the test case, for example:
/* $Id$ */

package my.package;

import my.package.BaseTestCase;
import my.package.MyClassToTest;

/**
* A unit test.
*
* @author Zeger Hendrikse
* @version $Revision$
*/
public class TestMyClassToTest extends BaseSdcmBusinessTestCase {

/** Object to test. */
private MyClassToTest myClassToTest;

public void testMyMethod() {
assertEquals("Number of items", 3, myClassToTest.getItems().size());
// Assert other fields too
}
.
.
.
As can be seen, the myClassToTest object will automatically be instantiated from the Spring application context as initialized in the super class. Here Spring will look for a bean definition with the same name: myClassToTest. Note that the associated setter has been omitted from this example for the sake of clarity.

References


Comments:

Post a Comment:
Comments are closed for this entry.

Hire us
Archives
Tags
Links
Stats
Referrers