Mockito - Throwing Exceptions by using thenThrow()

Mockito - Throwing Exceptions by using thenThrow()

Example 1

This is the perfect scenario when you just need to Stub an object and test something with this stubbed object

Example 2

But sometimes you just need to test a situation when things goes wrong 🙁

In that scenario, you might be worried about what will happen if a specific Exception been thrown by your code

With Mockito we just need to use the thenThrow() method as you can see below

Example 3

But if you run the previous code, your test will not pass 🙁

This happens because Mockito didn't know that you was really expecting that Exception.

To fix that, we can use the @Test(expected) approach, and we will let Mockito know about the expected Exception that will be thrown by the method

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: