Reputation: 25950
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 ?
Upvotes: 3
Views: 1309
Reputation: 21
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);
Upvotes: 1
Reputation: 7212
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
Upvotes: 1