ericj
ericj

Reputation: 2301

When can I write Mockito.anyInt()?

This is what I understand:

Mockito.when(list.get(Mockito.anyInt())).thenReturn("Foo Bar");
Assert.assertEquals("Foo Bar",list.get(7));

Accidentaly, I saw that I also can do,

Mockito.anyInt();
Mockito.when(list.get(13)).thenReturn("Foo Bar");
Assert.assertEquals("Foo Bar",list.get(7));

But I cannot to the following,

Mockito.anyInt();
Mockito.verify(list).get(5);

instead of

Mockito.verify(list).get(Mockito.anyInt());

which is OK. Why not?

Upvotes: 1

Views: 712

Answers (1)

Szymon Włodarczyk
Szymon Włodarczyk

Reputation: 127

Mockito.anyInt() is used for mock behavior recording or verifing.

Mockito.when(list.get(Mockito.anyInt())).thenReturn("Foo Bar");

Means while invoking get on list with any Integer value "Foo Bar" string will be returned.

Mockito.verify(list).get(Mockito.anyInt());

Is correct usage and means that list.get() was invoked exactly once with any Integer value.

Upvotes: 1

Related Questions