Easier Unit Testing in Spring
If you are using the Spring Framework, you should using Spring’s JUnit-based testing framework. See their docs for details.
I’ll try to do a summary for the rest of what it is and why you would want to use it instead of plain JUnit.
Here is a skeleton of the unit test class:
// AbstractDependencyInjectionSpringContextTests is in spring-mock.jarpublic class TestMyClass extends AbstractDependencyInjectionSpringContextTests { // classID must match the a bean ID in your Spring Configuration protected MyClass classID; // use the constructor just like the setUp method in JUnit public TestMyClass() { // this will populate all the protected objects setPopulateProtectedVariables(true); // this will find the class by name (i.e. bean ID) as opposed // to class-type setAutowireMode(AbstractDependencyInjectionSpringContextTests.AUTOWIRE_BY_NAME); } // this tells this class where to find the Spring configuration protected String[] getConfigLocations() { return new String[] { "classpath:appConfig.xml" }; } //** put your tests here public void testNormal(){ classID.someMethod(); // .... }
The AbstractDependencyInjectionSpringContextTests that TestMyClass extends has some very cool features. As the comments in the class above state, the protected classID object will automatically be populated with a new MyClass object – no need to fetch an ApplicationContext, get a bean, cast it, and then test it. If you want an ApplicationContext, the AbstractDependencyInjectionSpringContextTests gives you an instance called applicationContext that already is instantiated.
Did I mention that AbstractDependencyInjectionSpringContextTests is actually a subclass of JUnit’s TestCase? So you can still use the unit testing functionality in Eclipse and the junit tasks in ant.
I haven’t messed with it yet, but Spring also has an object called AbstractTransactionalDataSourceSpringContextTests that lets you poke around at the database within a test, rollback transactions, etc. Read more about it
in the Spring Docs.
Powered by ScribeFire.