Thursday, September 18, 2008

[Spring 2.5] How to create test case that calls class hierachy that uses spring injection

If you want to test a method on a class that uses a number of other classes, some utilizing spring, some not, you can use the following approach.
The example below is just written from memory and has not been verified compile wise, etc. If you find something strange, please comment. :)

import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations = { "classpath:applicationContext.xml" })public class MyTest extends TestCase {   @Test   public void testComplexClassStructure() {      // Test the class that relies on a number of       // other clasases, some using spring, some not.   }}

To make sure you can use spring inside your test class, add the @RunWith(SpringJUnit4ClassRunner.class). This will wrap your test with the Spring test class.

In order to load the applicationContext.xml (enable annotations in packages, etc), use the @ContextConfiguration(locations = { "classpath:applicationContext.xml" })

Add @Test to specify a test case.

If you are using maven (what a stupid question, of course you are), you need to add the following to your pom.xml for the above to work:
 org.springframework spring 2.5.1 org.springframework spring-test 2.5.1

For examples on applicationContext.xml and injection using @AutoWire, check this

No comments: