Reputation: 1964
Calling method on spy object somehow has no effect on real spied object:
public class AAA {
public int a;
public void setA(int aa) {
this.a = aa;
}
public int getA() {
return a;
}
}
public class Proof {
@Test
public void wtf() {
AAA obj = new AAA();
AAA spy = Mockito.spy(obj);
spy.setA(22);
assertThat(obj.getA(), equalTo(22));
}
}
How can that be? I suppose Proof
test should pass.
Upvotes: 6
Views: 1101
Reputation: 1629
As seen in the Mockito doc:
Mockito does not delegate calls to the passed real instance, instead it actually creates a copy of it.
This means that the original object obj
isn't modify with what happens in the spied object spy
.
Upvotes: 5
Reputation: 26522
I did some tests and you should make the assert on spy not an obj:
@Test
public void wtf() {
AAA obj = new AAA();
AAA spy = Mockito.spy(obj);
spy.setA(22);
assertThat(spy.getA(), equalTo(22));
}
Upvotes: 2