Three ways to mock an object using Mockito

Last Updated on

Creating Mock Objects

If you’re new to Mockito and have only seen a sample or two on the Internet, you might find other examples create mock objects in different ways using the same framework. As a matter of fact, there are three (3) ways to create mock objects in Mockito:

  1. Using the static method org.mockito.Mockito.mock(…)
  2. Using @Mock and calling MockitoAnnotations.initMocks(…) before anything else in @Before method
  3. Using @Mock with @RunWith(MockitoJUnitRunner.class)

On this article, we’ll be using version 2.0.2-beta which is the latest version as of this writing. I recommend using a more stable version in real-life applications. We’ll also use JUnit 4.12.

Software Requirements

  1. Java 7
  2. Eclipse Luna
  3. Mockito 2.0.2-beta
  4. JUnit 4.12
  5. Maven

Mocking Objects with static method Mockito.mock(…)

Mocking Objects with @Mock and MockitoAnnotations.initMocks(…)

Using @Mock with @RunWith(MockitoJUnitRunner.class)

Download the source code files



Karl San Gabriel

Professional Software Developer