Java 如何使模拟方法返回相同的模拟

Java 如何使模拟方法返回相同的模拟,java,mocking,mockito,Java,Mocking,Mockito,我试图模拟一个包含clone方法的类。我希望克隆返回相同的模拟: when(regressor.cloneWithSharedResources()).thenReturn(regressor); 但是,这会返回一个不同的对象。有什么方便的方法吗?也许我误解了你的问题,因为我无法重现这种行为 我创建了一个简单的测试来复制它: public class FooTest { class Regressor { public Regressor cloneWithSharedRes

我试图模拟一个包含
clone
方法的类。我希望克隆返回相同的模拟:

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

但是,这会返回一个不同的对象。有什么方便的方法吗?

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

我创建了一个简单的测试来复制它:

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);
   }
}
此测试成功通过,因此
回归器
克隆回归器
实际上是同一个对象

t = mock(Tester.class);
when(t.clone()).thenReturn(t);
拜托,你能告诉我是我错了还是我误解了什么吗。希望能有帮助


注意:我已经用Mockito 1.9.4进行了测试,我相信它必须给出相同的对象。你能发布你的代码吗。我试过下面的代码,它给了我相同的对象

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

创建模拟实例时,它看起来如何?是否实际调用了“cloneWithSharedResources”方法?返回什么类型的对象?你提供的代码对我来说很合适。这是一个模拟,因此实际的方法永远不会被调用。抱歉,现在无法回答,我稍后会检查,谢谢你的回答。事实证明,我没有调用
Mockito。请验证我认为的模拟上的
。这个mock本身是由另一个mock返回的,我搞错了应该调用的方法的(重载)签名并返回它。结果,我得到了一个不同的嘲笑,打破了我的假设。干杯:)对不起,现在无法回答,我稍后再查,谢谢你的回答