2

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?

Anton
  • 2,282
  • 26
  • 43
  • Never tried it but imho it will fail; `spy()` creates a proxy and I don't believe the proxy copies the fields over. – fge May 21 '14 at 19:51
  • 1
    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. – ndrone May 21 '14 at 20:10
  • Uhwell OK, I stand corrected then... But I usually don't play with instance fields like this :) – fge May 21 '14 at 20:11
  • ...What if you execute that code, then `println` `realClass.justAField' and `spyClass.justAField`? Then your question (what does the `realClass.justAField`) will be answered – Mike Koch May 22 '14 at 00:17
  • @ohiocowboy If you post that as an answer, I'll accept it. – Anton May 22 '14 at 18:22

1 Answers1

1

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

ndrone
  • 3,524
  • 2
  • 23
  • 37