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?
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.
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.
Mockito uses the BDDMockito class that is available in the org.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With