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

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

问题描述

我想将一个Mockito模拟对象注入一个Spring(3+)bean中,用于使用JUnit进行单元测试。我的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天全站免登陆