Archiv für den Monat: November 2013

Creating spring context with mocked beans

In my projects I create some integrative tests which should base on the original spring context definition. A small number of these tests are very useful in order to test the integration of the application. Even thought these test are integrative and in principle I do not want to mock away anything there are some beans in the context for which it is more practicable to mock them away. An example of this kind of beans is a mailer-service: The complexity and robustness of these tests is clearly decrease when this bean is mocked away.

Surprisingly, I could not found a description how you could create a spring context which is nearly untouched except of one single bean. But, there is a very simple way how you could create this kind of spring context for an integrative test:


@Test
public void testSomething()
{
   final Mockery mockery = new Mockery();
   final IMailer mailer = mockery.mock(IMailer.class);

   final ApplicationContext context = createContext("mailer", mailer);

   // do some tests using the context
}

private ApplicationContext createContext(
                            final String beanName, final Object object)
{
   return new ClassPathXmlApplicationContext(
                          new String[] { "applicationContext.xml" })
   {
      @Override
      protected void postProcessBeanFactory(
                          ConfigurableListableBeanFactory beanFactory)
      {
         beanFactory.registerSingleton(beanName, object);
      }
   };
}

That’s it all! As you can see, you only have to overwrite the method postProcessBeanFactory() and call the method registerSingleton() inside it. Obviously, this example can simply be extended such that more than one single mock-object is injected into the context.