Monday, January 14, 2013

Workaround for @ContextConfiguration restriction

One of the restrictions when using @ContextConfiguration to specify the location of Spring bean configurations for a Spring based JUnit test is that only one of either the locations attribute(or default value attribute) OR  classes attribute can be specified at a time.

Essentially the following will not run, as both classes and locations attribute is being specified here.

@WebAppConfiguration
@ContextConfiguration(classes=WebConfig.class, locations={"classpath:/META-INF/spring/applicationContext-security.xml", "classpath:/META-INF/spring/applicationContext.xml", "classpath:/META-INF/spring/applicationContext-jpa.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
public class MemberJsonControllerTest {
....

}


I am not completely sure why this restriction exists, but a workaround for this is to have an alternate application context where the java configuration and the locations based xml configuration is imported, and to use this new context for tests.

The simplest way is to not specify any attributes for @ContextConfiguration at all, this way the default behavior is to look for any static inner class annotated with @Configuration in the test class and import the other bean definition configurations into the @Configuration class this way:

@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
public class MemberJsonControllerTest {
....


 @Configuration
 @Import(WebConfig.class)
 @ImportResource({"classpath:/META-INF/spring/applicationContext-security.xml", 
      "classpath:/META-INF/spring/applicationContext.xml", 
      "classpath:/META-INF/spring/applicationContext-jpa.xml"})
 public static class ContextConfig{
  
 }
}

1 comment: