The location of a xml based test application context can be specified using the locations attribute:
1 | @ContextConfiguration (locations={ "test-context.xml" }) |
and if @Configuration is used as the context, then a classes attibute can be specified:
1 | @ContextConfiguration (classes={TestConfiguration. class }) |
There are intelligent defaults for these attributes though and that is what I wanted to highlight in this post.
If the locations or the classes attribute is not specified, the default behavior is to first look for a xml configuration with a name as the test class name - "context.xml" file
For eg. if I have a Test class this way:
1 2 3 | @RunWith (SpringJUnit4ClassRunner. class ) @ContextConfiguration public class TestSpringCache { |
The location of the configuration that will be tried first is "TestSpringCache-context.xml"
If a context is not found at this location, then a @Configuration default is looked for by scanning all static inner classes annotated with @Configuration of the test class. So if I had the following:
1 2 3 4 5 6 7 8 9 10 | @RunWith (SpringJUnit4ClassRunner. class ) @ContextConfiguration public class TestSpringCache { ... @Configuration @EnableCaching @ComponentScan ( "org.bk.samples.cache" ) public static class TestConfiguration{ .. |
The default behaviour can be changed by supplying a loader attribute to the @ContextConfiguration, say for eg, if I want to default to @Configuration with its defaults, it can done this way:
1 2 3 4 | @RunWith (SpringJUnit4ClassRunner. class ) @ContextConfiguration (loader=AnnotationConfigContextLoader. class ) public class TestSpringCache { .. |
So to conclude, the defaults provided by @Configuration are a great way to make the tests a little more concise!
No comments:
Post a Comment