Mockito - Basic usage of when() and thenReturn() methods

Mockito - Basic usage of when() and thenReturn() methods

Example 1

This example is showing us how to Stub a method. Stub here means the you will create a fake behavior based on your rule.

In out scenario, we are asking for Mockito:

  • Hey Mockito, please, when the method findNameById() is called with the value 25, then return the name "Hacking Code - Google Guava"

As you can see, we taught the Mockito what we are excepting for when the method findNameById is called

Example 2

As you can see in this example, we didn't teach to Mockito what we will expect when the method is called with the value 19

We just taught to Mockito about the value 25, therefore Mockito will say for you:

  • Hey, I have no idea what I need to do with the value 19! So, I will return a null value for you 🙁

Auxiliar UserDatabase class

That's it! I hope that this article can be really useful to you!

Thanks!

Alexandre Gama

Alexandre Gama

Hacking Code Founder

Hacking Code Founder and Writer, Passionate Senior Software Engineer and Team Leader at @Elo7, Teacher of several courses at Caelum, Speaker at many conferences and terrible guitar player.
Mockito Tutorial - Mocking Objects by using mock and verify - Java Guide by Hacking Code

Mockito - Mocking Objects by using mock() and verify()

Lear how to use Argument Matcher in its Fundamental way

Mockito Tutorial - Basic Usage of by when and thenReturn - Java Guide by Hacking Code

Mockito - Basic usage of when() and thenReturn() methods

Lear how to use Argument Matcher in its Fundamental way

Mockito Tutorial - Throwing Exceptions - Java Guide by Hacking Code

Mockito - Throwing Exceptions by using thenThrow()

Lear how to use Argument Matcher in its Fundamental way

Mockito Tutorial - Stubbing With Fluent Interface - Java Guide by Live Coding

Mockito - Stubying with Fluent Interface

Lear how to use Argument Matcher in its Fundamental way

Mockito Tutorial - Resetting Mock Interactions - Java Guide by Live Coding

Mockito - Reseting Mock Interactions

Lear how to use Argument Matcher in its Fundamental way

Mockito Tutorial - Ignoring Stubs - Java Guide by Hacking Code

Mockito - Ignoring Stubs Tutorial

Lear how to use Argument Matcher in its Fundamental way

Mockito Tutorial - BDD - Java Guide by Hacking Code

Mockito BDD - Behavior Driven Development with Mockito

Lear how to use Argument Matcher in its Fundamental way

Mockito Tutorial - Printing Custom Message - Java Tutorial by Hacking Code

Mockito - Printing Custom Message when the Verify fails

Lear how to use Argument Matcher in its Fundamental way

0 Comments

Leave a Reply

Share This
Subscribe To Our Newsletter

Subscribe To Our Newsletter

Join our mailing list to receive the latest news and updates from our team.

You have Successfully Subscribed!

%d bloggers like this: