Mockito单步执行失败?

2024-01-06

好吧,这很奇怪。 Mockito,Java,在 Windows 上。

 when(mongoTemplate.findAndModify(any(Query.class), any(Update.class), any(FindAndModifyOptions.class), eq(Task.class)))
            .thenReturn(t1)
            .thenReturn(t2);

现在,如果我在调试模式下运行它,它就可以正常工作。但是,如果我在时间上设置断点,并且单步执行,则会失败。

IntelliJ 中的错误是

org.mockito.exceptions.misusing.WrongTypeOfReturnValue: 
Task cannot be returned by toString()
toString() should return String
***
If you're unsure why you're getting above error read on.
Due to the nature of the syntax above problem might occur because:
1. This exception *might* occur in wrongly written multi-threaded tests.
   Please refer to Mockito FAQ on limitations of concurrency testing. 
2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies - 
 - with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.

因此,这可能是与 IntelliJ 的一些交互,希望在单步执行时“toString()”结果。也许 Mockito 需要在 OngoingStubbing 上捕获并回退到 toString ?


这种行为是故意的,而且必须是,否则toString将无法使用或无法使用。

Mockito 存根工作通过副作用和代理 https://stackoverflow.com/q/14440270/1426891。对于像您这样的电话:

 when(mongoTemplate.findAndModify(any(Query.class), any(Update.class), any(FindAndModifyOptions.class), eq(Task.class)))
            .thenReturn(t1)
            .thenReturn(t2);

Mockito 利用了可预测的 Java 执行顺序,它按顺序计算方法参数,然后调用方法本身,因此它会看到:

  1. any(Query.class): 1 个匹配器参数匹配器堆栈 https://stackoverflow.com/q/22822512/1426891, 返回null
  2. any(Update.class): 堆栈上有2个匹配器,返回null
  3. any(FindAndModifyOptions.class): 堆栈上有3个匹配器,返回null
  4. eq(Task.class): 堆栈上有4个匹配器,返回null
  5. findAndModify(null, null, null, null): 返回什么findAndModify返回,findAndModify现在是最近一次通话
  6. when:我们现在正在嘲笑最近的电话findAndModify使用四个参数匹配器,重置堆栈
  7. thenReturn(t1):在存根链上添加一个操作when
  8. thenReturn(t2):在存根链上添加一个操作when

如果您的 IDE 调用toString在步骤 5 和 6 之间,那么 Mockito 会假设您调用了findAndModify(null, null, null, null)有意提前并正在努力stub toString https://groups.google.com/g/mockito/c/y8Pou35-TBw/m/XG4zBIM-CG0J现在。既然你想回来t1,这意味着 Mockito 会告诉您,您的存根toString()需要一个字符串,但收到一个任务。

虽然这很烦人,但可以说比 Mockito 拒绝存根更不烦人toString(),或者如果您完全无法致电toString()在模拟上。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Mockito单步执行失败? 的相关文章

随机推荐