Mockito单元测试-放错位置的参数匹配器

问题描述 投票:0回答:1

我有一个具有MVP体系结构的应用程序,其中包括以下两种方法:在Presenter类中:

override fun callSetRecyclerAdapter() {
    view.setRecyclerAdapter()
    view.setRefreshingFalse()
}

并且在Model类中

override fun handleApiResponse(result : Result) {
    articleList = result.articles
    presenter.callSetRecyclerAdapter()
}

重点是我想进行一个测试,检查articleList中的handleApiResponse是否为空,无法继续编码

我尝试通过此测试类来完成它:

lateinit var newsModel: NewsModel
@Mock
lateinit var newsPresenter : NewsPresenter

@Before
fun setUp() {
    MockitoAnnotations.initMocks(this)
    newsModel = NewsModel(newsPresenter)
}

@Test
    fun makeRequestReturnNull() {
        newsModel.handleApiResponse(Result(ArgumentMatchers.anyList()))
        verify(newsPresenter, never()).callSetRecyclerAdapter()
    }

但是启动后,我在运行屏幕中收到此错误消息:

Misplaced or misused argument matcher detected here:

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.
java unit-testing mockito mockito-kotlin
1个回答
0
投票

您正在使用anyList()作为被测方法的参数-

newsModel.handleApiResponse(Result(ArgumentMatchers.anyList()))

anyX API应该用于模拟/验证对模拟实例的调用。它显然不是“真实”对象,因此无法在Mockito范围之外的调用中使用。您需要使用实际参数调用此方法,并使用Mockito来控制任何依赖项行为,以确保您仅测试代码。

© www.soinside.com 2019 - 2024. All rights reserved.