0

I have a following line using Mockito:

when(mock.method()).thenReturn(foo).thenReturn(bar).thenThrow(new Exception("test"));

Is the above statement same as:

when(mock.method()).thenReturn(foo)thenThrow(new Exception("test"));
when(mock.method()).thenReturn(bar).thenThrow(new Exception("test"));

Please can anyone explain me, how would thenReturn be executed? How does it work?

hc_dev
  • 8,389
  • 1
  • 26
  • 38

1 Answers1

1

A quick look in Mockito's documentation will provide the answer.

 //you can set different behavior for consecutive method calls.
//Last stubbing (e.g: thenReturn("foo")) determines the behavior of further consecutive calls.
when(mock.someMethod("some arg"))
.thenThrow(new RuntimeException())
.thenReturn("foo");

//Alternative, shorter version for consecutive stubbing:
when(mock.someMethod("some arg"))
.thenReturn("one", "two");
//is the same as:
when(mock.someMethod("some arg"))
.thenReturn("one")
.thenReturn("two");

Basically, calling the thenReturn multiple times will define how the method will behave in multiple calls.

Vitor Santos
  • 581
  • 4
  • 15