javamockitospy

Changing fields of a mockito spy


So lets say I have a class

class JustAClass() {
  Stirng justAField = "nothing";
}

Now I'm testing this class and I put it into a mock

JustAClass realClass = newJustACLass();
JustAClass spyClass = Mockito.spy(realClass);

spyClass.justAField = "something"

Question is: What does the realClass.justAField equal now?

EDIT: In response to @fge This didn't fail.

    CSVExport spyClass = Mockito.spy(testClass);
    FileOutputStream wFile = Mockito.mock(FileOutputStream.class);

    spyClass.wFile = wFile;

    Mockito.doThrow(IOException.class).when(spyClass).createBlankWorkbook();
    spyClass.export(testEnabledFields);
    Mockito.doThrow(IOException.class).when(wFile).close();
    spyClass.export(testEnabledFields);

So is the wFile in testClass the mock now, or the original?


Solution

  • Pulling this from api doc http://docs.mockito.googlecode.com/hg-history/be6d53f62790ac7c9cf07c32485343ce94e1b563/1.9.5/org/mockito/Spy.html

    Mockito does not delegate calls to the passed real instance, instead it actually creates a copy of it. So if you keep the real instance and interact with it, don't expect the spied to be aware of those interaction and their effect on real instance state. The corollary is that when an unstubbed method is called on the spy but not on the real instance, you won't see any effects on the real instance