gpt4 book ai didi

java - Mockito 单元测试 - 错误放置或误用参数匹配器

转载 作者:行者123 更新时间:2023-12-02 09:21:13 25 4
gpt4 key购买 nike

我有一个具有 MVP 架构的应用程序,其中包括以下两种方法:在演示者类中:

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

在模型类中

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

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

我尝试用这个测试类来做到这一点:

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.

最佳答案

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

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

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

关于java - Mockito 单元测试 - 错误放置或误用参数匹配器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58680366/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com