I have a method that call a void function in it, and when I use doNothing()
, it says that void method it's not allowed. How could I doNothing()
in that specific line?
I'm using this line,
when(spyColorSelector.initializeColors(view, "red")).then(doNothing());
Mockito provides following methods that can be used to mock void methods. doAnswer() : We can use this to perform some operations when a mocked object method is called that is returning void. doThrow() : We can use doThrow() when we want to stub a void method that throws exception.
You just need to use @Mock annotation to mock the object. I am testing doNothing() both on dao and service class' methods.
Use Stubber syntax :
doNothing().when(spyColorSelector).initializeColors(view, "red");
And spyColorSelector
has to be a mock.
Edit 1: code example with spy.
This test works (no exception thrown by initializeColors
) with JUnit 4.12 and 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);
// Then
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 be called");
}
}
Edit 2: new example without spy.
If you really want initializeColors
not to be executed in the test, I think there is a design issue in the ColorSelector
class. The initializeColors
method should be in another class X, and there would be a dependency of class X in ColorSelector
class which you could stub in your test (and then 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 the default behavior of a mock is to do nothing
colorSelector.colorInitializer = colorInitializerMock;
// When
LinkedList<Integer> colors = colorSelector.getColors(color, view);
// Then
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) {
// Do something
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With