将 Mockito 模拟注入 Spring bean [英] Injecting Mockito mocks into a Spring bean

查看:36
本文介绍了将 Mockito 模拟注入 Spring bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了使用 JUnit 进行单元测试,我想将 Mockito 模拟对象注入 Spring (3+) bean.我的 bean 依赖项目前是通过在私有成员字段上使用 @Autowired 注释注入的.

I would like to inject a Mockito mock object into a Spring (3+) bean for the purposes of unit testing with JUnit. My bean dependencies are currently injected by using the @Autowired annotation on private member fields.

我已经考虑使用 ReflectionTestUtils.setField 但我希望注入的 bean 实例实际上是一个代理,因此没有声明目标类的私有成员字段.我不希望为依赖项创建公共设置器,因为我将纯粹出于测试目的修改我的界面.

I have considered using ReflectionTestUtils.setField but the bean instance that I wish to inject is actually a proxy and hence does not declare the private member fields of the target class. I do not wish to create a public setter to the dependency as I will then be modifying my interface purely for the purposes of testing.

我遵循了 Spring 社区提供的一些建议但是没有创建模拟并且自动接线失败:

I have followed some advice given by the Spring community but the mock does not get created and the auto-wiring fails:

<bean id="dao" class="org.mockito.Mockito" factory-method="mock">
    <constructor-arg value="com.package.Dao" />
</bean>

我目前遇到的错误如下:

The error I currently encounter is as follows:

...
Caused by: org...NoSuchBeanDefinitionException:
    No matching bean of type [com.package.Dao] found for dependency:
    expected at least 1 bean which qualifies as autowire candidate for this dependency.
    Dependency annotations: {
        @org...Autowired(required=true),
        @org...Qualifier(value=dao)
    }
at org...DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(D...y.java:901)
at org...DefaultListableBeanFactory.doResolveDependency(D...y.java:770)

如果我将 constructor-arg 值设置为无效的值,则在启动应用程序上下文时不会发生错误.

If I set the constructor-arg value to something invalid no error occurs when starting the application context.

推荐答案

最好的方法是:

<bean id="dao" class="org.mockito.Mockito" factory-method="mock"> 
    <constructor-arg value="com.package.Dao" /> 
</bean> 

更新
在上下文文件中,此模拟必须在声明任何依赖于它的自动装配字段之前列出.

Update
In the context file this mock must be listed before any autowired field depending on it is declared.

这篇关于将 Mockito 模拟注入 Spring bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆