Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatic mock instantiation in a Spring JUnit test

I have a Spring XML bean definition that I want to write integration tests for. The XML bean definition is part of a larger application context where several such files are included using <import>. Inside the definition, I reference several beans that are coming from other files.

For my integration test I would like to instantiate the definition standalone and use Mockito mocks for all other beans. Until now, I am using something like this:

FooIntegrationTest.java

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class FooIntegrationTest {
  @Autowired private ClassUnderTest underTest;
  @Autowired private MockedClass mock;

  @Test
  public void testFoo() {
  }
}

FooIntegrationTest-context.xml

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:c="http://www.springframework.org/schema/c"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
  <import resource="part-to-test.xml" />

  <bean id="mockedClassReferencedByName" class="org.mockito.Mockito" factory-method="mock" c:classToMock="SomeMockedClass" />
  <bean class="org.mockito.Mockito" factory-method="mock" c:classToMock="OtherMockedClassReferencedByType" />
  <bean class="org.mockito.Mockito" factory-method="mock" c:classToMock="MockedClass" />
  ...
</beans>

I would like to automate the rather tedious mocking section: Ideally, I would like to have all beans that are not found in the application context to be mocked automatically. The part-to-test.xml uses @Autowired as well as beans that are set by using name references. I only use XML bean definition files, and neither use @Configuration classes nor @Component annotations.

I have looked into how to use a custom context loader in @ContextConfiguration(loader=...), but I have not yet found an appropriate extension point for doing so. Sprinockito does not seem to adress this problem.

Is there some other project out there that already solves this problem? If not, where would I extend Spring to create the mocks automatically?

like image 292
nd. Avatar asked Apr 20 '12 13:04

nd.


1 Answers

Here is a short article with a code example. A BeanDefinitionRegistryPostProcessor implementation generates a mock object for each lacking bean definition. The generation part is done with a MocksFactory, here is an example for such a factory.

like image 141
Yves Martin Avatar answered Sep 20 '22 17:09

Yves Martin