如何在java中模拟单个方法

是否可以模拟Java类的单个方法?

例如:

class A { long method1(); String method2(); int method3(); } // in some other class class B { void someMethod(A a) { // how would I mock A.method1(...) such that a.method1() returns a value of my // choosing; // whilst leaving a.method2() and a.method3() untouched. } } 

使用Mockito's间谍机制:

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

使用spy会为任何非stubed方法调用包装对象的默认行为。

Mockito.spy() / @Spy

使用Mockito中的spy()方法 ,并像这样模拟你的方法:

 import static org.mockito.Mockito.*; ... A a = spy(new A()); when(a.method1()).thenReturn(10L); 

假设您正在使用jmockit:

 public void testCase(@Mocked("methodToBeMocked") final ClassBoBeMocked mockedInstance) { new Expectations() {{ mockedInstance.methodToBeMocked(someParameter); returns(whateverYouLikeItToReturn); }} mockedInstance.callSomemethod(); } 

您可以简单地创建一个覆盖method1()A的子类。