In this chapter, we will cover the following recipes:
Mockito, as the name suggests, is all about working with mocks. It is worth mentioning that before you go and start mocking every class that is in your codebase, it's good to really understand the idea behind mocking and when to mock an object.
While performing unit testing, you will want to test your system in isolation. You're doing it because you want to test a part of the system as a unit and control any external interactions. Remember that in new, well-designed code, your system should follow the SOLID principles (for more details, check out Uncle Bob's blog at http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod and read Agile Software Development, Principles, Patterns, and Practices, Robert C. Martin, which is available at http://www.amazon.com/Software-Development-Principles-Patterns-Practices/dp/0135974445). The complete description about what SOLID stands for is given as follows:
Assuming that we follow the SOLID principles, we have a class that is dependent on some other components where each component is responsible for a single functionality. When testing that class (if it makes sense, of course), we can create test doubles (to check out the differences between different types of test doubles (refer to Chapter 1, Getting Started with Mockito) for the components that are passed as collaborators (most probably through constructors). Here, Mockito comes to the rescue and helps you easily create mocks for those components.
The next chapter focuses on showing tests created to test some real-life examples of production code simplified for the sake of readability). We will focus on numerous ways of creating mocks (in the majority of cases, you should be using only the default annotation-based approach).
A standard reminder that you will see throughout the book is as follows:
Because I am very fond of behavior-driven development (http://dannorth.net/introducing-bdd/ first introduced by Dan North), I'm using Mockito's BDDMockito
and AssertJ's BDDAssertions
static methods in all the test cases to make the code even more readable and intuitive. Also, please read Szczepan Faber's blog (author of Mockito) about the given, when, then separation in your test methods, from http://monkeyisland.pl/2009/12/07/given-when-then-forever/, since these separation methods are omnipresent throughout the book.
Even though some of the mentioned methods might sound not too clear to you, or the test code will look complicated, don't worry, it will all be explained through the course of this book. I don't want the book to become a duplication of the Mockito documentation. I would like you to take a look at nice tests and get acquainted with Mockito syntax from the very beginning. I have used static imports in the code to make it even more readable, so if you get confused with any of the pieces of code, it would be best to refer to the repository and the code as such.
18.116.49.247