mockito spy不会在android studio上工作

时间:2018-01-18 09:36:23

标签: mockito spy

我试图模拟一些对象并操纵对象方法的返回值。在应用间谍或模拟之后,似乎操纵返回值并不起作用。最后的结果' res'不是' 10'正如我所料,但是' 1'。在实例化B类并调用方法getAAA()之后,它只调用A.aaa()的实际方法并返回' 1'。

    class A {
        public int aaa() { return 1; }
    }

    class B {
        A classA;

        B(A classA) { this.classA = classA; }

        public int getAAA() { return classA.aaa(); }
    }

    A spyA = mock(A.class);
    when(spyA.aaa()).thenReturn(10);

    A AA = new A();
    int res = new B(AA).getAAA();
    Logxx.d("RESULT: " + res);

结果:1​​

1 个答案:

答案 0 :(得分:0)

您没有使用模拟/间谍,而是使用新创建新对象 此外,您正在使用mock(...)模拟对象,但您将对象称为间谍(spyA)。这没有错,因为它只是一个变量名。但不可读。

    A mockA = mock(A.class);
    when(spyA.aaa()).thenReturn(10);

    A AA = new A();
    int res = new B(mockA).getAAA();
    Logxx.d("RESULT: " + res);