android - How to doNothing() on void method? -
i have method call void function in it, , when use donothing()
, says void method it's not allowed. how donothing()
in specific line?
i'm using line,
when(spycolorselector.initializecolors(view, "red")).then(donothing());
use stubber syntax :
donothing().when(spycolorselector).initializecolors(view, "red");
and spycolorselector
has mock.
edit 1: code example spy.
this test works (no exception thrown initializecolors
) junit 4.12 , mockito 1.10.19:
public class colorselectortest { @test public void testgetcolors() { // given string color = "red"; view view = mock(view.class); colorselector colorselector = new colorselector(); colorselector spycolorselector = spy(colorselector); donothing().when(spycolorselector).initializecolors(view, color); // when linkedlist<integer> colors = spycolorselector.getcolors(color, view); // assertnotnull(colors); } } class colorselector { public linkedlist<integer> getcolors(string color, view view) { this.initializecolors(view, color); return new linkedlist<>(); } void initializecolors(view view, string color) { throw new unsupportedoperationexception("should not called"); } }
edit 2: new example without spy.
if want initializecolors
not executed in test, think there design issue in colorselector
class. initializecolors
method should in class x, , there dependency of class x in colorselector
class stub in test (and no need of spy). basic example:
public class colorselectortest { @test public void testgetcolors() { // given string color = "red"; view view = mock(view.class); colorselector colorselector = new colorselector(); colorinitializer colorinitializermock = mock(colorinitializer.class); donothing().when(colorinitializermock).initializecolors(view, color); // optional because default behavior of mock nothing colorselector.colorinitializer = colorinitializermock; // when linkedlist<integer> colors = colorselector.getcolors(color, view); // assertnotnull(colors); } } class colorselector { colorinitializer colorinitializer; public linkedlist<integer> getcolors(string color, view view) { colorinitializer.initializecolors(view, color); return new linkedlist<>(); } } class colorinitializer { public void initializecolors(view view, string color) { // } }
Comments
Post a Comment