Thursday 3 November 2011

Spring with easymock

I was busy the other day setting up my spring environment so I could inject a load of easymock objects into my spring beans. After a bit of a google it turns out its really easy!

To override a bean in a test you just need to insert the following classpath override annotation into your junit test class and point it to your XML file with the spring bean you want to make an easymock object redefined therein.

@ContextConfiguration(locations = { "classpath:persistenceOverride.xml" })
public class MyTest extends AbstractJUnit4SpringContextTests
{
    @Test
    public void yourTestHere()
    {
    }
}

and the xml...
<beans xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/tx 
    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
    http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
    http://www.springframework.org/schema/jee 
    http://www.springframework.org/schema/jee/spring-jee-3.0.xsd 
    http://www.springframework.org/schema/util 
    http://www.springframework.org/schema/util/spring-util-3.0.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">


 <bean class="org.easymock.EasyMock" factory-method="createStrictMock" id="entityManagerFactory">
  <constructor-arg type="java.lang.Class" value="javax.persistence.EntityManagerFactory"> </constructor-arg>
</bean> 
</beans> 

The things to node here are the factory-method definition that lets spring know how we want to create our mocked entity manager factory (i.e. org.easymock.EasyMock.createStrickMock(javax.persistence.EntityManagerFactory.class());