Mockito为什么认为此自动装配的bean为空? [英] Why does Mockito think this autowired bean is null?

查看:258
本文介绍了Mockito为什么认为此自动装配的bean为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个叫做restTemplate的类.它是Spring框架中的RestTemplate对象.我正在尝试在Mockito测试的设置方法的开头重置它,但出现异常:

I have this class called restTemplate. It is a RestTemplate object from the Spring Framework. I am trying to reset it in the beginning of a setup method for my Mockito test but I get the exception:

org.mockito.exceptions.misusing.NotAMockException: Argument should be a mock, but is null!


那么我在做什么错呢?我在


So what am I doing wrong? I have the correct packages listed under

<context:component-scan base-package = "..."/>

它被自动装配到我的测试类中,并在我的applicationContext-test.xml文件中列出.首先我应该看什么?

It is autowired into my test class and is listed in my applicationContext-test.xml file. What should I be looking at first?

<bean id="restTemplate" class="org.mockito.Mockito" factory-method="mock">
    <constructor-arg value="org.springframework.web.client.RestTemplate" />
</bean>

推荐答案

每个API:

Per the API: Mockito.mock takes an instance of Class<?> but in your spring config you are passing a String that is the fully qualified name of a class but it is not a Class<?> instance.

这引出了一个问题,为什么要在Spring配置中设置模拟?为什么不只是在测试中实例化被测类并在那里创建模拟.模拟是为您进行单元测试而设计的.如果要加载上下文,则可能正在进行集成测试.并不是说在JUnit测试中加载上下文是一件坏事,但是在其中使用Mocks似乎是很复杂的事情.

It begs the question, why are you setting up mocks in your Spring config? Why not just instantiate the class under test in your test and create the mock there. Mocks are designed you unit testing. If you are loading the context you are probably approaching integration testing. Not that loading a context in a JUnit test is a bad thing, but using Mocks in them seems to be mixing things.

但是,如果您真的想尝试,可以尝试使用

HOWEVER, if you really want to try it, you might try something like declaring a bean that is the class instance using Class.forName as the factory method. Something like:

<bean id="classInstance" class="java.lang.Class" factory-method="forName">
    <constructor-arg value="org.springframework.web.client.RestTemplate" /> 
</bean>


<bean id="restTemplate" class="org.mockito.Mockito" factory-method="mock">
    <constructor-arg ref="classInstance" /> 
</bean>

这篇关于Mockito为什么认为此自动装配的bean为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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