简体   繁体   中英

Mockito unit tests - missplaced or missused argument matcher

I have an application with MVP architecture which includes these two methods: In Presenter class:

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

And in Model class

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

The point is that I want to make a test which checks if articleList in handleApiResponse is null it couldn't go code further

I tried doing it with this test 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()
    }

But after launching I get this error message in run screen:

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.

You are using anyList() as an argument to the method under test -

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

the anyX API should be used to mock/verify calls made to a mocked instance. It is obviously not a "real" object and therefore cannot be used in a call outside the Mockito scope. You need to call this method with an actual argument and use Mockito to control any dependency behaviour to make sure you are only testing your code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM