wilddev wilddev - 1 year ago 72
Java Question

Mockito.spy not changing real object

Calling method on spy object some how 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 {
public void wtf() {
AAA obj = new AAA();
AAA spy = Mockito.spy(obj);


assertThat(obj.getA(), equalTo(22));

How can that be? I suppose Proof test should pass.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download