Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito: given versus when

In order to stub methods when using JUnit and Mockito, it's possible to use two ways:

when(foo.doSomething()).thenReturn(somethingElse); 

and

given(foo.doSomething()).willReturn(somethingElse); 

Are there any differences between these two stubs?

like image 688
Rollerball Avatar asked Nov 05 '15 13:11

Rollerball


People also ask

What is given in Mockito?

Behavior Driven Development is a style of writing tests uses given, when and then format as test methods. Mockito provides special methods to do so.

What is the use of when in Mockito?

Mockito when() method It enables stubbing methods. It should be used when we want to mock to return specific values when particular methods are called. In simple terms, "When the XYZ() method is called, then return ABC." It is mostly used when there is some condition to execute.

Is Mockito TDD or BDD?

Mockito uses the BDDMockito class that is available in the org.

When return vs do return in Mockito?

The two syntaxes for stubbing are roughly equivalent. However, you can always use doReturn/when for stubbing; but there are cases where you can't use when/thenReturn . Stubbing void methods is one such. Others include use with Mockito spies, and stubbing the same method more than once.


1 Answers

I assume you are talking about Mockito syntax.

From my point of view these are just different styles. The first is the normal Mockito syntax and the second just tries to fit nicer into BDD style tests - I really like the second version because it reads so nicely in BDD tests.

like image 104
Mathias Dpunkt Avatar answered Sep 30 '22 05:09

Mathias Dpunkt