【问题标题】:Why does Mockito think this autowired bean is null?为什么 Mockito 认为这个自动装配的 bean 是空的?
【发布时间】:2012-10-11 20:01:21
【问题描述】:

我有这个类叫做restTemplate。它是 Spring Framework 中的 RestTemplate 对象。我正在尝试在 Mockito 测试的设置方法开始时重置它,但出现异常:

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


那么我做错了什么?我在

下列出了正确的软件包
<context:component-scan base-package = "..."/>

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

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

【问题讨论】:

  • 如何在 XML 中定义 RestTemplate 模拟?它也可能被 Spring 代理。
  • 它在编辑中。感谢您的回复。
  • 你能在reset()之前打印restTemplate.toString()吗?也尝试将RestTemplate 替换为RestOperations?最后,您可以尝试在重置之前使用unwrapProxy() 方法从此处:stackoverflow.com/questions/8121551 处理注入的模拟吗?

标签: spring junit mockito


【解决方案1】:

根据 API:Mockito.mock 采用 Class&lt;?&gt; 的实例,但在您的 spring 配置中,您传递了一个 String,它是类的完全限定名称,但它不是 Class&lt;?&gt; 实例。

这引出了一个问题,为什么要在 Spring 配置中设置模拟?为什么不在您的测试中实例化被测类并在那里创建模拟。模拟是为您设计的单元测试。如果您正在加载上下文,您可能正在接近集成测试。并不是说在 JUnit 测试中加载上下文是一件坏事,而是在其中使用 Mocks 似乎是混合了一些东西。

但是,如果您真的想尝试它,您可以尝试使用 Class.forName 作为工厂方法声明一个作为类实例的 bean。比如:

<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>

【讨论】:

    猜你喜欢
    • 2018-04-16
    • 2013-09-28
    • 2014-09-08
    • 1970-01-01
    • 2019-04-04
    • 2015-12-10
    • 2021-09-02
    • 2015-12-02
    • 2022-01-14
    相关资源
    最近更新 更多