Categories
Archives
Formatting Debug Output with print_r( | Home | A jQuery Tip: Don't Use jQuery
Filed under Quick Tips on May 14, 2008 by Doug BurnsUnit Testing with JUnit 4 and Spring
I really like Java annotations for reducing XML configuration and simplifying code. Spring 2.5 introduced a new annotation-based unit test framework that further improved the great one it already provided. Using this, along with JUnit 4, you can create Spring unit tests without having to subclass anything.
An example unit test is shown below, along with an explanation of the annotations used.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:/applicationContext.xml"})
public class ExampleTest
{
ExampleObject objectUnderTest;
@Test
public void testSomethingTrue() {
Assert.assertNotNull(objectUnderTest);
Assert.assertTrue(objectUnderTest.getSomethingTrue());
}
@Test
@Ignore
public void testSomethingElse() {
Assert.assertNotNull(objectUnderTest);
Assert.assertTrue(objectUnderTest.getSomethingFalse());
}
@Autowired
public void setObjectUnderTest(ExampleObject objectUnderTest)
{
this.objectUnderTest = objectUnderTest;
}
}
-
@RunWith- JUnit annotation that specifies that the Spring class runner should be used for running the test. -
@ContextConfiguration- Specifies the location of your Spring application context xml file(s). This gets inherited by subclasses, so you can use it in a base class to configure all of the tests in your application. -
@Test- Indicates that the method should be run as a test. Note that although I used the pre JUnit 4 naming conventions (class names postfixed with "Test" and method names prefixed with "test"), this is not a requirement. -
@Ignore- When this annotation is added, the associated test method will not be run. This is a great alternative to commenting out the methods which was required prior to JUnit 4. In this case, the test would fail if the @Ignore annotation wasn't used because objectUnderTest.getSomethingFalse() does not equal true. -
@Autowired- Indicates that Spring should "wire" this dependency when initializing the test. In this case, a Spring bean named objectUnderTest will be provided.
Trackback Pings (TrackBack URL for this entry)
http://www.arc90.com/cgi-bin/mt4/mt-tb.cgi/150.
Formatting Debug Output with print_r( | Main | A jQuery Tip: Don't Use jQuery
