Specifying classes loading order in @ContextConfiguration in JUnit test cases

10k views Asked by At

I am using junit 4.11 and spring-test-4.1.5 for writing integration test cases. I am using @ContextConfiguration annotation to load the configurations.like,

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes ={ApplicationConfig.class,SpringConfiguration.class }, initializers = {CustomProfileResolver.class, AppInitializer.class}, loader = SpringApplicationContextLoader.class)

As you can see i am using two configuration classes. The problem i am facing is i want to load the SpringConfiguration.class before ApplicationConfig.class. I tried with reversing the order but it didn't worked. Neither @order can be specified here.

So how to order the loading of these configuration classes, is it possible ?

2

There are 2 answers

1
R.A On

Use @ContextHierarchy

@ContextHierarchy({
   @ContextConfiguration(classes = {SpringConfiguration.class}),
   @ContextConfiguration(classes = {ApplicationConfig.class})
}
0
Sam Brannen On

@ContextConfiguration and its supporting classes (e.g., MergedContextConfiguration, AnnotationConfigContextLoader, AbstractTestContextBootstrapper, etc.) are intended to retain the original ordering of @Configuration classes declared via the classes attribute of @ContextConfiguration.

Thus, if you can verifiably prove that reversing the order of your SpringConfiguration and ApplicationConfig classes does not result in SpringConfiguration being processed first, then you have found a bug in Spring.

If you have found a bug, please report it in JIRA.

Thanks,

Sam