spring - Spring JUnit 测试中的自动模拟实例化

我有一个 Spring XML bean 定义,我想为其编写集成测试。 XML bean 定义是更大的应用程序上下文的一部分,其中使用 <import> 包含几个这样的文件。 .在定义中,我引用了几个来自其他文件的 bean。

对于我的集成测试,我想独立实例化定义,并对所有其他 bean 使用 Mockito 模拟。到目前为止,我使用的是这样的:

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类(class)或 @Component注释。

我在 @ContextConfiguration(loader=...) 中研究了如何使用自定义上下文加载器。 ,但我还没有找到合适的扩展点。 Sprinockito 似乎没有解决这个问题。

是否有其他项目已经解决了这个问题?如果没有,我将在哪里扩展 Spring 以自动创建模拟?

最佳答案

这里是 short article with a code example . BeanDefinitionRegistryPostProcessor 实现为每个缺少的 bean 定义生成一个模拟对象。生成部分使用 MocksFactory 完成,这里是 an example for such a factory .

https://stackoverflow.com/questions/10247297/

相关文章:

java - Spring 验证与 Hibernate 验证

java - 使用具有不同 AuthenticationProviders 的多个 WebSecur

java - Spring Security 3 - 总是返回错误 302

java - 使用spring boot(安全)和keycloak启用角色身份验证?

spring - jar 如何在使用它的 Web 应用程序中传播漏洞?

java - 使用 Spring JavaConfig 和 @Autowired 注入(inject

spring - 如何在运行时将新用户添加到 Spring Security

java - Spring WS : How to get and save XSD validat

java - 在 Spring Hibernate java 项目中使用 "Envers"审计表

java - Spring Integration Kafka Consumer Listener