Chapters

Hide chapters

Android Test-Driven Development by Tutorials

Second Edition · Android 11 · Kotlin 1.5 · Android Studio 4.2.1

Section II: Testing on a New Project

Section 2: 8 chapters
Show chapters Hide chapters

Section III: TDD on Legacy Projects

Section 3: 8 chapters
Show chapters Hide chapters

7. Introduction to Mockito
Written by Fernando Sproviero

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

You’ll often find yourself in situations in which you want to write a test for a method of a class that requires collaboration from another class. Unit Tests normally focus on a single class, therefore you need a way to avoid using their actual collaborators. Otherwise, you’d be doing integration testing, which you’ll see in Chapter 8, “Integration.”

In this chapter, you’ll:

  • Learn what mocking and stubbing are and when to use these techniques.
  • Write more unit tests using the test-driven development (TDD) pattern to continue testing state, and a way to also verify behavior.

Why Mockito?

If you remember from a previous chapter, whenever you create a test, you must:

  • First, configure what you’re going to test.
  • Second, execute the method that you want to test.
  • Finally, verify the result by checking the state of the object under test. This is called state verification or black-box testing. This is what you’ve done using JUnit.

However, to perform state verification, sometimes the object under test has to collaborate with another one. Because you want to focus on the first object, in the configuration phase, you want to provide a test double collaborator to your object under test. This fake collaborator is just for testing purposes and you configure it to behave as you want. For example, you could make a mock so that calling a method on it always returns the same hardcoded String. This is called stubbing a method. You’ll use Mockito for this.

There’s another type of verification called behavior verification or white-box testing. Here you want to ensure that your object under test will call specific collaborator methods. For example, you may have a repository object that retrieves the data from the network, and before returning the results, it calls a collaborator object to save them into a database. Again, you can use Mockito to keep an eye on a collaborator and verify if specific methods were called on it.

Note: Using white-box testing allows you to be more precise in your tests, but often results in having make more changes to your tests when you change your production code.

Setting up Mockito

Open the application’s build.gradle file and add the following dependency:

Creating unit tests with Mockito

Later, in the UI, you’ll show the user a question with two options. You’ll want the user to click on one. Your Game class will then handle that answer by delegating to the Question class. The score will be incremented if the answer was correct and the next question will be returned.

Mocking and verifying

Start by adding the following test to the GameUnitTests.kt file:

Using mock-maker-inline extension

  • Go to the project window and change to the Project view.
  • Create a resources directory under app ‣ src ‣ test.
  • Inside resources, create a directory called mockito-extensions
  • Add a text file called org.mockito.plugins.MockMaker
  • Add the text mock-maker-inline

Taxi uj wtijug lkir ag job adxownogv oj evwavepuix le zfa abwver() lixgud od qjo Nievgies framy.

Stubbing methods

The Game should increment the current score when answered correctly, so add the following test:

Refactoring

Open the Game class. Notice that this class knows about the score and a list of questions. When requesting to answer a question, the Game class delegates this to the Question class and increments the score if the answer was correct. Game could also be refactored to delegate the logic of incrementing the current score and highest score to a new class, Score.

Verifying in order

To save and retrieve the high score, you’ll need to add functionality to a repository. From the Project view, create a new package common ‣ repository under app ‣ src ‣ test ‣ java ‣ com ‣ raywenderlich ‣ android ‣ cocktails. Create a new file called RepositoryUnitTests.kt and add the following code:

Spying

Suppose you want to only save the high score if it is higher than the previously saved high score. To do that, you want to start by adding the following test to your RepositoryUnitTests class:

Stubbing callbacks

Create a new test that verifies that the callback is called when the repository returns successfully with a list of cocktails in CocktailsGameFactoryUnitTests.kt:

Testing ViewModel and LiveData

To update the UI with questions, the score, and also to enable the user to interact with the question options, you’re going to use ViewModel and LiveData from Android Architecture Components.

Mockito annotations

Instead of calling the mock() and spy() methods, you can use annotations. For example, open RepositoryUnitTests.kt and modify the class definition, variable definitions and setup functions to look like the following:

Sobu Yykuit
Felu Mvzuem

Challenge

Challenge: Writing another test

  • When answering incorrectly three times, it should finish the game.
  • When answering correctly three times sequentially, it should start giving double score.

Key points

  • With JUnit you can do state verification, also called black-box testing.
  • With Mockito you can perform behavior verification or white-box testing.
  • Using a mock of a class will let you stub methods simulate a particular situation in a test. It’ll also verify if one or more methods were called on that mock.
  • Using a spy is similar to using a mock, but on real instances. You’ll be able to stub a method and verify if a method was called just like a mock, but also be able to call the real methods of the instance.
  • Remember: Red, Green, Refactor

Where to go from here?

Awesome! You’ve just learned the basics of unit testing with Mockito.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2026 Kodeco Inc.

You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now