How to mock a single method in java

后端 未结 4 1793
执念已碎
执念已碎 2020-12-13 09:09

Is it possible to Mock a single method of a Java class?

For example:

class A {
    long method1();
    String method2();
    int method3();
}


// in         


        
4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-13 09:48

    Use Mockito's spy mechanism:

    A a = new A();
    A aSpy = Mockito.spy(a);
    Mockito.when(aSpy.method1()).thenReturn(5l);
    

    The use of a spy calls the default behavior of the wrapped object for any method that is not stubbed.

    Mockito.spy()/@Spy

提交回复
热议问题