Asiemie
Asiemie

Reputation: 45

Mockito .thenReturn(list.add()) actually adds something to my list

I am trying to test one of my functions, which adds something to a database if a condition is true. Now in my test class I am trying to mock this on a list:

List list = new ArrayList();
String myString  = "";

when(xxx.addToDatabase()).thenReturn(list.add(myString));

So if my condition is true this assertion should be correct:

AssertTrue(list.contains(Object)).

And if my condition is false this assertion should apply:

AssertFalse(list.contains(Object));

So my problem is, that the my list always contains the Object, since the .thenReturn seems to be called even if it's not actually called.

Is there a way to prevent the list.add() being called?

Upvotes: 0

Views: 4677

Answers (2)

pvpkiran
pvpkiran

Reputation: 27068

This is what you should be doing.

List<> someList = new ArrayList();
doAnswer(invocation -> {
    someList.add(myString);
     // return something
    }).when(xxx).addToDatabase();

Upvotes: 0

glytching
glytching

Reputation: 47935

This line:

when(xxx.addToDatabase()).thenReturn(list.add(myString));

... is invoked in your test regardless of whether xxx.addToDatabase() is invoked in the code under test.

So, you are adding myString to list in your test case. This explains the following:

my list always contains the Object

Re this:

Is there a way to prevent the list.add() being called?

I think there might be some misunderstanding of how to use a mock here.

The following line ...

when(xxx.addToDatabase()).thenReturn(list.add(myString));

... means: when xxx.addToDatabase() is invoked then return true since list.add() returns a boolean. I suspect that what you want to happen is to perform list.add as a side effect of xxx.addToDatabase(). If so, then you may want to use doAnswer instead of doReturn. If you update your question with a MCVE it will be easier to guide you.

Upvotes: 1

Related Questions