簡體   English   中英

Mockito 單元測試 - 錯誤放置或錯誤使用的參數匹配器

[英]Mockito unit tests - missplaced or missused argument matcher

我有一個 MVP 架構的應用程序,其中包括這兩種方法: 在 Presenter class 中:

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

並在 Model class

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

關鍵是我想做一個測試來檢查articleList中的handleApiResponse是否是null 它不能進一步編碼go

我試着用這個測試 class 來做:

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 應該用於模擬/驗證對模擬實例的調用。 它顯然不是“真正的”object,因此不能在 Mockito scope 之外的呼叫中使用。 您需要使用實際參數調用此方法並使用 Mockito 來控制任何依賴行為,以確保您只測試代碼

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM