如何使模拟方法 return 成为相同的模拟

How to make a mocked method return the same mock

我正在尝试模拟一个包含 clone 方法的 class。我希望克隆 return 相同的模拟 :

when(regressor.cloneWithSharedResources()).thenReturn(regressor);

然而,这个return对我来说是一个不同的对象。有什么方便的方法吗?

也许我误解了你的问题,因为我无法重现这种行为。

我创建了一个简单的测试来重现它:

public class FooTest {
   class Regressor {
      public Regressor cloneWithSharedResources() {
         return new Regressor();
      }
   }

   class ClassToTest {
      public Regressor foo(Regressor regressor) {
         // ...
         return regressor.cloneWithSharedResources();
      }
   }

   @Test
   public void testFoo() throws Exception {
      Regressor regressor = Mockito.mock(Regressor.class);
      Mockito.when(regressor.cloneWithSharedResources()).thenReturn(regressor);

      ClassToTest classToTest = new ClassToTest();
      Regressor clonedRegressor = classToTest.foo(regressor);

      Assert.assertSame(regressor, clonedRegressor);
   }
}

这个测试成功通过,所以regressorclonedRegressor实际上是同一个对象。

拜托,如果我错了或者我误解了什么,你能告诉我吗?希望对你有帮助。

注意:我用Mockito 1.9.4

测试过

我相信它必须给出相同的对象。你能 post 你的代码吗?我试过下面的代码,它给了我同样的对象。

t = mock(Tester.class);
when(t.clone()).thenReturn(t);