How to mock a single method in java

后端 未结 4 1794
执念已碎
执念已碎 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:40

    Use the spy() method from Mockito, and mock your method like this:

    import static org.mockito.Mockito.*;
    
    ...
    
    A a = spy(new A());
    when(a.method1()).thenReturn(10L);
    
    0 讨论(0)
  • 2020-12-13 09:41

    You could simply create a subclass of A that overrides method1().

    0 讨论(0)
  • 2020-12-13 09:47

    Assuming you are using jmockit:

    public void testCase(@Mocked("methodToBeMocked") final ClassBoBeMocked mockedInstance) {
               new Expectations() {{
                       mockedInstance.methodToBeMocked(someParameter); returns(whateverYouLikeItToReturn);
               }}
    
       mockedInstance.callSomemethod();
    }
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题