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{
  
 }
}

2 comments:

  1. 2017-05-05 13:27:03,068 [main] WARN org.springframework.web.context.support.GenericWebApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Only one AsyncAnnotationBeanPostProcessor may exist within the context.
    Offending resource: URL [file:/C:/work/codespace/git/auca_service/target/test-classes/applicationContext_test.xml]

    ReplyDelete