Getting friendly with Spring, JUnit and EasyMock.

Written by DanEngland

August 1st, 2009 at 8:31 pm

Posted in java

Tagged with , ,

With no comments

Here are some steps that can get you using Spring, JUnit and EasyMock all together in some Test Driven Development hotness.

Start by adding the following lines to the top of your unit test. Specifying Autowire by name ensures you get the injection you want and will stop those Spring errors that there are more than one of the same type of mock objects in your mock-applicationContext.xml. When you specify the Spring Junit runner you must provide one ore more context configurations with @ContextConfiguration.

MyClassUnitTest.java

...
@Configurable(autowire = Autowire.BY_NAME)
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:com/some/domain/someproject/resources/mock-applicationContext.xml"})
public class MyClassUnitTest {
...
     @Autowired private Collaborator mockCollaborator;

     @Before
     public void setup() throws Exception {
     ...
     }

     @After
     public void teardown() throws Exception {
     ...
     }

     @Test
     public void testMyClass() throws Exception {

          //Set your mock behavior here
          ....

          EasyMock.replay(mockCollaborator);

          MyClass myClass = new MyClass(mockCollaborator);
          myClass.run();
          EasyMock.verify(mockCollaborator);

          // Other JUnit assertions
          ...
     }
 }

Then add your mocks to your mock-applicationContext.xml (an applicationContext in your test resources just for providing your unit tests with spring injection dependencies):

mock-applicationContext.xml

...
<bean id="mockCollaborator" name="mockCollaborator" class="org.easymock.EasyMock" factory-method="createStrictMock">
     <constructor-arg value="com.some.domain.someproject.Collaborator"/>
</bean>

<bean id="mockOtherCollaborator" name="mockOtherCollaborator" class="org.easymock.EasyMock" factory-method="createStrictMock">
     <constructor-arg value="com.some.domain.someproject.OtherCollaborator"/>
</bean>
...

Ensure your maven pom has the following test-scoped dependency:

pom.xml

...
<dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-test</artifactId>
     <version>2.5.6</version>
     <scope>test</scope>
</dependency>
...

Then use your mocks as normal. Make sure you call EasyMock.reset(mock) in your @After teardown() method so that each of your mocks are reset for each test. You can also tell Spring to reset the context after a test if needed with @DirtiesContext.

For official documentation and tutorials check out these links.

Spring

http://www.springsource.org/documentation

JUnit

http://www.junit.org

EasyMock

http://easymock.org/Documentation.html

  • Share/Bookmark

Related Posts

Comments

Leave a Reply