本文介绍了注射嘲笑的Mockito成一个Spring bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想注入一个模拟的Mockito对象到春季(3+)豆与JUnit单元测试的目的。我的豆依赖目前使用的私有成员字段中的 @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实例实际上是一个代理,因此没有声明目标类的私有成员字段。我不希望建立一个公共的setter的依赖,因为我将被修改纯属我的接口,用于测试的目的。

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)

如果我设置了构造带参数价值的东西无效启动应用程序上下文时发生错误。

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 21:39