Jarek
Jarek

Reputation: 7729

Dynamicaly changing behavior of mocks in Mockito

Hello I would like to know, if there is any way to dynamicaly modify behaviour of mocks in Mockito.

For example I have a method count() and I would like Mockito to return a value higher by one every time I call it on mock.

Thank you.

Upvotes: 3

Views: 4494

Answers (2)

Jens Kreidler
Jens Kreidler

Reputation: 480

Of course, for your count()-method getting an increment the Mockito-Answer is the best way.

BTW: But nevertheless remind that you can 'change' (define) the behaviour of a mocked-method in case of subsequent invocations:

when(mock.someMethod("some arg"))
.thenThrow(new RuntimeException())
.thenReturn("foo");

Here you see first invocation throws a RuntimeException, the second invocation returns the String "foo" ...

Upvotes: 4

Charlie
Charlie

Reputation: 7349

Yes... Create an Answer and stub it out on your mock using doAnswer().

Upvotes: 6

Related Questions