javamockitospy

Mockito verify works on mock but not on spy


I have a problem with mockito#spy it does not work. I have boiled down the problem to this:

var list = (ArrayList<String>) Mockito.mock(ArrayList.class);
var spyList = Mockito.spy(list);

list.add("test");
Mockito.verify(spyList).add("test");

Howerver, if I verify on the Mock itself, it does work:

var list = (ArrayList<String>) Mockito.mock(ArrayList.class);
//var spyList = Mockito.spy(list);

list.add("test");
Mockito.verify(list).add("test");

I want to use spy on a real object of course, but for the sake of finding my problem, I am using a mock for now.

I am using Junit 5.7.1 and Mockito 3.3.3. Those are pretty much set in stone I'm afraid.

Any suggestion what could be the problem?


Solution

  • Your test is wrong; you are attempting to use the Mock object (named list) as a Spy object (which is named spyList).

    Try this:

    spyList.add("test");
    Mockito.verify(spyList).add("test");