dimanche 13 novembre 2016

Stop mocked object from firing void method during "when"

There's a question here which seeks to answer this. But the answers don't seem to cover the case of an (injected) mock with specifically a void method which gets called.

In my app code there is a line:

indexWriter.commit();

...where indexWriter (class IndexWriter) is a private field (hence the use of injection) of class IndexManager. commit() is a void return method in the class IndexWriter.

In my testing class I do this:

@Mock
private IndexWriter mockedIndexWriter;

and

@InjectMocks
IndexManager injectedIM = new IndexManager();

When it comes to my test method I simply want the mocked IndexWriter to do absolutely nothing when commit() is called on it. So I go:

doNothing().when( mockedIndexWriter ).commit();

... but unfortunately this calls the commit method at this point in the code, and due to other mocks therefore throws an Exception.

PS Incidentally I thought of making my mocked IndexWriter a @Spy rather than a @Mock. But it wouldn't let me do that, seemingly because the IndexWriter class doesn't have a parameterless constructor.

Aucun commentaire:

Enregistrer un commentaire