Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 404
wilddev Avatar asked Mar 09 '23 22:03

wilddev


2 Answers

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.

like image 90
Sergio Lema Avatar answered Mar 21 '23 12:03

Sergio Lema


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));
    }
like image 43
Maciej Kowalski Avatar answered Mar 21 '23 10:03

Maciej Kowalski