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

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

我正在使用这条线,

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

解决方法:

使用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
    }
}
上一篇:Mockmvc put方法不起作用的春天


下一篇:java – 如何在Mockito中存储varargs以仅匹配一个参数