如何在void方法上执行Nothing()?

时间:2015-07-22 16:03:43

标签: android unit-testing testing mockito

我有一个调用void函数的方法,当我使用doNothing()时,它表示不允许使用void方法。我怎么能doNothing()在那个特定的行?

我正在使用这一行,

when(spyColorSelector.initializeColors(view, "red")).then(doNothing());

1 个答案:

答案 0 :(得分:7)

使用Stubber语法:

doNothing().when(spyColorSelector).initializeColors(view, "red");

并且spyColorSelector必须是模拟。

编辑1:使用间谍的代码示例。

使用JUnit 4.12和Mockito 1.10.19进行此测试(initializeColors抛出没有异常):

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");
    }
}

编辑2:没有间谍的新例子。

如果您真的希望在测试中不执行initializeColors,我认为ColorSelector类中存在设计问题。 initializeColors方法应该在另一个类X中,并且在ColorSelector类中将存在类X的依赖关系,您可以在测试中存根(然后不需要间谍)。基本示例:

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
    }
}