wilddev
wilddev

Reputation: 1964

Mockito.spy not changing real object

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

Answers (2)

Sergio Lema
Sergio Lema

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

Maciej Kowalski
Maciej Kowalski

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

Related Questions