繁体   English   中英

如何使mocked方法返回相同的mock

[英]How to make a mocked method return the same mock

我试图模拟一个包含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);
   }
}

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

拜托,你能告诉我,如果我错了,或者我误会了什么。 希望能帮助到你。

注意 :我已经使用Mockito 1.9.4进行了测试

我相信它必须给出同样的目标。 你可以发布你的代码吗? 我试过下面的代码,它给了我相同的对象。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM