I was just working on a JUnit test today, and saw the annotation
To instruct Spring to load beans for the tests in the class, we annotate the class with
There can be various ways we can use this annotation, lets have a look at it one by one:
Suppose our class is Greeting.java and our context file is spring-context.xml
Again this is equivalent to fully qualified package path of Greeting class.
We can give fully qualified path of the spring-context file in this annotation.
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.
@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 Greeting.java and our context file is spring-context.xml
package com.vaani.contextconfig;Well this is equivalent to
@ContextConfiguration
public class Greeting{
...
}
@ContextConfiguration("/com/vaani/contextconfig/spring-context.xml")
public class Greeting{
File specified (without a starting Slash)
package com.vaani.contextconfig;
@ContextConfiguration("spring-context.xml")
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;
@ContextConfiguration("/com/vaani/contextconfig/spring-context.xml")
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