Spring JUnit测试中的自动模拟实例化
我有一个Spring XML bean定义,我想为其编写集成测试. XML bean定义是较大的应用程序上下文的一部分,其中使用<import>
包含了多个此类文件.在定义中,我引用了来自其他文件的几个bean.
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.
对于我的集成测试,我想独立地实例化定义,并对所有其他bean使用Mockito模拟.到目前为止,我使用的是这样的内容:
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>
我想使相当乏味的模拟部分自动化:理想情况下,我希望所有在应用程序上下文中找不到的bean都可以自动模拟. part-to-test.xml
使用@Autowired
以及使用名称引用设置的bean.我只使用XML bean定义文件,而没有使用@Configuration
类和@Component
批注.
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.
我已经研究了如何在@ContextConfiguration(loader=...)
中使用自定义上下文加载器,但尚未找到合适的扩展点. Sprinockito似乎没有解决这个问题.
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.
是否有其他一些已经解决了这个问题的项目?如果没有,我应该在哪里扩展Spring以自动创建模拟?
Is there some other project out there that already solves this problem? If not, where would I extend Spring to create the mocks automatically?
此处为简短带有代码示例的文章. BeanDefinitionRegistryPostProcessor
实现为每个缺少的bean定义生成一个模拟对象.生成部分是用MocksFactory
完成的,这里是
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.