Mockito:无法模拟静态和非静态方法

Mockito: Unable to mock a static & non-static method

我无法从 mockito 模拟任何东西(静态或非静态方法),

这些是我的 class,

Calculations.java

public class Calculations {

    public void printZero() {
        System.out.println("zero");
    }

    public static void printOne() { 
         System.out.println("one");
    }
}

这是我的PostData.java

public class PostData {

    public static Calculations calc = new Calculations();
    public static void postTheData() {

        calc.printZero();
        Calculations.printOne();
    }
}

单元测试class, TestClass.java

public class TestClass {

    @Test
    public void addTest() {

        Calculations lmock = mock(Calculations.class);

        // can't have Calculations.calc.printZero() in when() :cause: argument passes to when() must be a mock object.
        doNothing().when(lmock).printZero();

        // cause: method when(void) is undefined for the type TestClass
        // when(lmock.printZero()).doNothing();

        // cause: argument passed to when() must be a mock object.
        // doNothing().when(Calculations.printOne());

        PostData.postTheData();
    }
}

它已编译并在我的输出中打印 "zero" 和 "one",理想情况下应该被忽略。

我正在为 mockito 使用 cloud-mockito-all-1.10。19.jar。 还有junit最新的jar文件。

我知道我在这里遗漏了一些东西,但不知道是什么!如果你能回答我,那将是一个很大的帮助。

问题是 PostData 没有使用模拟的 Calculations 对象。

为此,您可以为计算字段添加一个 setter(并可能将其更改为非静态)并将 PostDatacalc 字段设置为嘲笑一个。