简体   繁体   中英

How to make a mocked method return the same mock

I am trying to mock a class that contain a clone method. I want the clone to return the same mock :

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

However, this returns me a different object. Is there a convenient way to do that ?

Maybe I've misuderstood something about your question because I'm unable to reproduce this behaviour.

I've created a simple test to reproduce it:

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);
   }
}

This test passes successfully, so regressor and clonedRegressor are actually the same object.

Please, could you tell me if I'm wrong or I've misunderstooed something. Hope it helps.

NOTE : I've tested with Mockito 1.9.4

I believe it has to give same object. Can you post your code. i have tried below code and it gives me the same object.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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