Thursday, June 2, 2011

@ContextConfiguration : Getting the context file via annotations in Spring, using JUnit

I was just working on a JUnit test today, and saw the annotation @ContextConfiguration which is good way of providing beans directly in unit test, rather than getting the bean via getBean or any method like we used to do (See here for these methods ). 
To instruct Spring to load beans for the tests in the class, we annotate the class with @ContextConfiguration.
There can be various ways we can use this annotation, lets have a look at it one by one:

No File Specified

@ContextConfiguration – with no parameters, (by Default) looks for the config file as the same name as the class with the suffix “-context.xml“. For example,
Suppose our class is and our context file is spring-context.xml

package com.vaani.contextconfig;
public class Greeting{
Well this is equivalent to

public class Greeting{

File specified (without a starting Slash)

package com.vaani.contextconfig;
public class Greeting{

Again this is equivalent to fully qualified package path of Greeting class.

File specified with a Starting Slash

One Simple change can ruin your whole day! Add a Starting Slash to the file name.
package com.vaani.contextconfig;
public class Greeting{

We can give fully qualified path of the spring-context file in this annotation.

Multiple Files

Pulling multiple configuration files into the application context for your tests.
@ContextConfiguration(locations = {"spring-context.xml", "other-context.xml"})

Just a tip
Create an XML file per test that imports only the application’s context files that are needed.
This can save test execution time, where we only load beans necessary for these tests.

No comments:

Post a Comment