首页 > 解决方案 > 如何将 @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方法是否正式支持这样的东西?

标签: mockito

解决方案


推荐阅读