Automatic mock instantiation in a Spring JUnit test

断了今生、忘了曾经 提交于 2019-11-30 01:48:30

问题


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?


回答1:


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.




回答2:


Just in case anyone is still interested in this question, I have extended the code in the article mentioned by Yves Martin with inheritance, support for @Inject, etc... and created a Github project here: https://github.com/rinoto/spring-auto-mock



来源:https://stackoverflow.com/questions/10247297/automatic-mock-instantiation-in-a-spring-junit-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!