Vlog-expan-image

Unit Testing with Mockito/PowerMockito

23 May 2024|5 min read|Shalaka Dharap

Is it daunting for you to perform unit testing in Java? Well, there is nothing to worry about, as many developers face this challenge. The good news is that a tool called Mockito can make this process much easier.

Mockito can fit into different roles within code, making it easier to isolate and test individual components. It is primarily a mocking framework that allows developers to write effective tests using simple and clean APIs for Java-based applications. It also integrates seamlessly with frameworks like JUnit and TestNG and supports mocks on any system, regardless of Java installation.

Using a mocking framework for unit testing has been one of the most effective software development practices, with Mockito leading the way in recent years. However, to promote better code design, some features were intentionally excluded — which sometimes forces developers to write additional code for advanced use cases.

That’s where PowerMockito comes into play!

Before diving into Mockito and PowerMockito, let’s start with the basics.

What is Unit Testing?

Unit testing involves breaking software components into small, isolated units for validation. Its goal is to verify that each unit of software meets functional and performance expectations. Typically, unit testing occurs early in development — before code integration — helping developers detect flaws early, reduce costs, improve quality, and enhance project efficiency.

What is Mocking?

In unit testing, dependencies are often replaced with controlled implementations to isolate the code under test. This is achieved through mocking. Mocking frameworks simplify the creation of mock objects and manage dependency behavior during testing.

Mocking is the process of creating controlled replacements for real objects. These mocks simulate the behavior of real components, allowing isolated testing of the unit under development. The main types of replacement objects are stubs, fakes, and mocks.

Mockito, PowerMock, and PowerMockito — The Connection

  • Mockito: A popular mocking framework offering functionalities such as mocking, stubbing, and verification. However, it doesn’t natively support mocking private or static methods.
  • PowerMock: Uses bytecode manipulation to mock constructors, static methods, and remove static initializers. However, it can sometimes lead to poor application design.
  • PowerMockito: An extension of Mockito that provides additional capabilities, especially for interacting with Java Reflection API to mock private, static, and final methods.

Decoding Unit Testing with Mockito & PowerMockito

Mockito is an open-source mocking framework in Java that simplifies writing unit tests. However, Mockito cannot mock private, final, or static methods — that’s where PowerMockito steps in. PowerMockito uses the Java Reflection API to handle these cases.

To use these frameworks, include the following Maven dependencies in your project:

Maven Dependencies

org.mockito
mockito-all
1.9.5
test

org.powermock
powermock-api-mockito
1.6.2
test

org.powermock
powermock-module-junit4
1.6.2
test
  

Common Annotations

  • @RunWith – Defines which test runner to use.
    For PowerMockito: @RunWith(PowerMockRunner.class) For Mockito: @RunWith(MockitoJUnitRunner.class)
  • @PrepareForTest – Used in PowerMockito to specify classes that require preparation using Java Reflection.
  • @Test – Marks a method as a JUnit test case.
  • @Mock – Creates mock objects directly via annotations.
  • @Spy – Spies on an existing object instance.
  • @Before – Initializes objects before running tests.

Generic Syntax for Mocking

To mock a method call:

PowerMockito.when(object.printMessage(Mockito.anyString())).thenReturn(message);
  

This returns the specified message whenever printMessage() is invoked with any string argument.

To mock static methods:

PowerMockito.mockStatic(PropertiesReader.class);
PowerMockito.when(PropertiesReader.getProperty(Constants.PAGE_SIZE)).thenReturn(ONE);
  

To mock new object creation:

PowerMockito.whenNew(ClassWithFinalMethods.class).withNoArguments().thenReturn(mockObject);
  

To set internal state of a mock:

Whitebox.setInternalState(mockVmReplication1, ID_PROPERTY, REPLICATION_ID1);
  

Calling Real Methods Using Mocked Objects

You can call real methods in two ways:

  1. Using doCallRealMethod()
    Mockito.when(mockObject.methodUnderTest()).thenCallRealMethod();
          
    This calls the actual method on a mocked object.
  2. Using actual object creation
    ClassUnderMock obj = new ClassUnderMock();
    obj.methodUnderTest();
          
Pros Cons
doCallRealMethod() does not create real objects. Actual object creation creates real instances, which is not recommended for mocks.
Real method calls avoid setting constructor variables manually. May require manually setting internal states of constructed objects.

Assert and Verify

Assert and Verify are used to validate mocking outcomes.

Common Assert methods:

  • Assert.assertEquals() – Fails when expected and actual values differ.
  • Assert.assertNotNull() – Fails when the actual value is null.
  • Assert.assertNotEquals() – Fails when expected and actual values are equal.
  • Assert.assertTrue() – Fails when condition is false.
  • Assert.assertFalse() – Fails when condition is true.

Using Verify()

Verify ensures the tested code behaves as expected.

Mockito.verify(mockedObject, Mockito.times(1)).methodUnderTest();
  

This verifies that methodUnderTest() was called exactly once on mockedObject. If not, it throws an error like “Wanted 2 times but was 1 time.”

In a Nutshell

Unit testing is an essential practice for ensuring each software component functions correctly. Mockito and PowerMockito are powerful frameworks that simplify this process. While Mockito provides simple APIs for general mocking, PowerMockito extends these capabilities to private, final, and static methods through the Java Reflection API.

By using these tools, developers can isolate and test code effectively, identify issues early, and maintain a cleaner, more reliable codebase. Incorporating Mockito and PowerMockito into your workflow enhances both productivity and software quality.

Calsoft offers state-of-the-art testing solutions by leveraging advanced frameworks and automation tools, helping businesses accelerate their journey from QA to QE.

Profile

Shalaka Dharap

Shalaka has 7 years of IT Industry experience and her primary Skills are JAVA development for the Telecom domain and security/storage domains.

Share:
Background Image

Want to create a connected, intelligent, & resilient manufacturing ecosystem?