Software Development

Three ways to mock an object using Mockito

Creating Mock Objects

If you’re new to Mockito, you might find other examples to create mock objects in different ways using the same framework. As a matter of fact, there are three ways to create mock objects in Mockito:

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

In 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

Using static method Mockito.mock(…)

Objects with @Mock and MockitoAnnotations.initMocks(…)

Using @Mock with @RunWith(MockitoJUnitRunner.class)

Download the source code files

The files are available on this link.

Got comments, or suggestions? Please visit our Facebook page!

You Might Also Like