10/28/2013

Junit Config @ContextConfiguration locations

When we run Junit test for services, if the service is configured using spring, we need to load the spring context first.

Normally, the way to configure the Junit test case is:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"config.xml"})
public class MessageServiceTest {

 private static final Logger logger = Logger.getLogger(MessageServiceTest.class);
 
 //MessageService service = new MessageServiceImpl();
 
 @Autowired
 MessageService service;
 
 @Test
 public void sendMessageTest() {
        //TODO-something
        }
}

If we are not clear of how spring look for context file, it's boring to have exceptions files not found blablabla...

Just make a summary here:

@ContextConfiguration(locations={"config.xml"})
=>This means to look for config.xml under the test package that holds currently running test case.

@ContextConfiguration(locations={"/config.xml"})
@ContextConfiguration(locations={"classfile:config.xml"})
=>These two equals, means to look for config.xml under the classpath. It could be under either 'src/main/resources' or 'src/test/resources' (By default) (If you change the classpath, then configure based on your own configuration.)

@ContextConfiguration(locations={"file:src/main/webapp/config.xml"})
=>This means to look for config.xml based on relative path to the project's base directory.


If wanna configure multiple config files, then
@ContextConfiguration
(
  {
   "classpath:beans.xml",
   "file:src/main/webapp/spring/applicationContext.xml",
   "file:src/main/webapp/spring/domain-config.xml",
   "file:src/main/webapp/spring/dispatcher-servlet.xml"
  }
)

Good Luck!



No comments:

Post a Comment