mockito - 如何将 @Before 方法中的 Mockito 1.x 模拟设置迁移到 Mockito 2.x?
问题描述
我正在尝试将数千个测试从 Mockito 1.x 迁移到 Mockito 2.x。一些测试(当前)将常见的模拟设置放在 @Before 方法中,比如:
@Before
public void before() {
//...
Mockito.when(something.doStuff(Mockito.<Boolean>any())).thenReturn(result);
//...
}
测试失败,如下所示:
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Misplaced or misused argument matcher detected here:
-> at ...SomeClassTest.before(SomeClassTest.java:<line-number>)
You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
when(mock.get(anyInt())).thenReturn(null);
doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());
verify(mock).someMethod(contains("foo"))
This message may appear after an NullPointerException if the last matcher is returning an object
like any() but the stubbed method signature expect a primitive argument, in this case,
use primitive alternatives.
when(mock.get(any())); // bad use, will raise NPE
when(mock.get(anyInt())); // correct usage use
Also, this error might show up because you use argument matchers with methods that cannot be mocked.
Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().
Mocking methods declared on non-public parent classes is not supported.
我不确定这是否在 @Before 方法中是原因,但看起来确实可能是原因,但我希望在我开始在其他地方挖掘之前得到一些快速的指示......
有谁知道@Before方法是否正式支持这样的东西?
解决方案
推荐阅读
- azure - 在 Azure Repo 上禁用推送时自动部署
- vb6 - AddressOf 运算符 VB6 的无效使用
- mysql - 使用 SQL 查询获取 mysql 表校验和
- c# - 如何在Web API项目的日志属性类中实现日志级别的条件?
- javascript - angular - ngif 条件内的主体标记类名称
- asp.net-core - 将 Tailwind CSS 放入 ASP.NET Core 项目的最佳方法是什么?
- python - 记录扭曲不打印到屏幕
- python - 将 pyhanlp 部署到 aws lambda 时出现 Errno 30
- c++ - 是否可以在 C++ 中返回带有科学计数法的双精度数?
- javascript - 如何使用 node.js 克隆 github 存储库