【问题标题】:Mockito NotAMockException when it clearly is显然是 Mockito NotAMockException
【发布时间】:2012-04-25 13:10:29
【问题描述】:

我正在使用 Spring Test 框架和 Junit。我有一个用于测试用例的 spring 上下文文件:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "classpath:spring/restTestContext.xml",
        "classpath:spring/webserviceContext.xml" })
@PrepareForTest(User.class)
public class RestTestsIT {

// This is a mock
@Autowired private AWSMailService mailService;
...
}

在 restTestContext.xml 中,我正在创建一个 AWSMailService 类型的 bean(实际上是一个模拟):

<bean id="mailService" name="mailService" class="org.mockito.Mockito" factory-method="mock">
    <constructor-arg value="com.acme.utils.email.AWSMailService" />
</bean>

在测试中,我试图验证在 mailService 模拟上调用了 sendEmail() 方法,但我得到了 NotAMockException,尽管在对象上调用 toString() 告诉我它是一个模拟:

public void testEmailSent() {
...
// Results in "Mock for AWSMailService, hashCode: 31777764"
System.out.println(mailService.toString());

// Results in NotAMockException
verify(mailService).sendEmail(any(String.class), ...);
}

有人知道是什么原因造成的吗?

谢谢

【问题讨论】:

  • 已修复 :) 显然我必须等待 8 小时才能回答我自己的问题,所以我明天会更新 :(

标签: junit mockito spring-test


【解决方案1】:

Spring 是否为这个对象创建了一个代理,所以 Mockito 认为它不是一个模拟,因为你得到一个 Proxy$34 类作为调用者和你的模拟对象之间的中间体?

【讨论】:

  • 没错,我通过手动连接模拟来解决它
【解决方案2】:

我遇到了同样的问题,我使用的是 mockito 1.8.1,在 1.9.0 版本中问题已得到修复。

现在 Mockito 的有效模拟算法已经改变,并且与 spring 代理 bean 没有冲突。

【讨论】:

    【解决方案3】:

    修复它:)

    问题在于,Mockito 确实在创建一个 Mock,但 Spring 正在代理它,而 Mockito 不够聪明,无法确定 Mock 周围有一个代理。

    我现在在单元测试中手动创建模拟并将它们连接起来:

    @Mock private AWSMailService mailService;
    @Autowired private UserService userService;
    
    @Before
    public void setup() {
      ((UserServiceImpl) userService).setMailService(mailService);
    }
    

    【讨论】:

      猜你喜欢
      • 2015-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多