DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • IntelliJ Integration for Mockito
  • Testing Business Programs Without Constructing Domain Objects
  • Why Standard Test Automation Misses the Failures That Matter in AI Agent Systems
  • More Tests, More Confidence? Test Suites Are Investment Portfolios

Trending

  • Why Successful Tech Transformation Starts With Clarity
  • Designing the Runtime Layer for Stateful AI Agents: Where Agent Substrate Fits
  • Stop Writing Database Migration Scripts: Declarative Schema Sync for Java
  • Your Event Storming Is Not Your Software Design

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. Unit Testing Static Methods With Mockito

Unit Testing Static Methods With Mockito

Unit testing can be hard especially when you need to test a method that is static, this tutorial will help you to easily mock static methods.

By 
Hakan Altındağ
·
Dec. 15, 20 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
39.4K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

Unit testing helps us to cover different scenarios and it is a way to ensure the applications behave as expected under certain circumstances. Most of the time it is easy to test your classes and methods, but sometimes you need to mock certain services or methods to isolate your target. Mockito is a good library to help you with that. It can easily create mocked or partially mocked objects for you with Mockito#mock or with Mockito#spy.

There are some cases that we also want to mock static methods of a particular utility class, so how can we accomplish that? Well by using the Mockito mockStatic method. Lets take an example by using the following AnimalUtils, Dog objects and Animal Interface:

Java
 




x


 
1
interface Animal {
2
    String getName();
3
}



Java
 




xxxxxxxxxx
1
13


 
1
class Dog implements Animal {
2

          
3
    String name;
4

          
5
    public Dog(String name) {
6
        this.name = name;
7
    }
8

          
9
    @Override
10
    public String getName() {
11
        return name;
12
    }
13
}



Java
 




x



1
public final class AnimalUtils {
2

          
3
    private AnimalUtils() {}
4

          
5
    public static Dog getGermanShepherd() {
6
        return new Dog("german shepherd");
7
    }
8

          
9
    public static Dog getKangal() {
10
        return new Dog("kangal");
11
    }
12

          
13
    public static Animal getAnimal() {
14
        return getGermanShepherd();
15
    }
16

          
17
}



The above AnimalUtils getAnimal method always invokes the getGermanShepherd method, but in a real use case scenario this could be a call to a service or to be more specific a database call or something else. We will mock the static method getGermanShepherd and preserve the behavior of the getAnimal method. In this way, we can isolate the getAnimal method and validate if that method is calling getGermanShepherd. See below for the unit test:

Java
 




xxxxxxxxxx
1
18


 
1
@Test
2
void animalUtilsTest() {
3
    Animal kangal = AnimalUtils.getKangal();
4

          
5
    try (MockedStatic<AnimalUtils> fooUtilsMocked = Mockito.mockStatic(AnimalUtils.class, invocation -> {
6
        Method method = invocation.getMethod();
7
        if ("getAnimal".equals(method.getName())) {
8
            return invocation.callRealMethod();
9
        } else {
10
            return invocation.getMock();
11
        }
12
    })) {
13
        fooUtilsMocked.when(AnimalUtils::getGermanShepherd).thenReturn(kangal);
14

          
15
        Animal animal = AnimalUtils.getAnimal();
16
        assertThat(animal.getName()).isEqualTo("kangal");
17
    }
18
}



unit test Mockito

Opinions expressed by DZone contributors are their own.

Related

  • IntelliJ Integration for Mockito
  • Testing Business Programs Without Constructing Domain Objects
  • Why Standard Test Automation Misses the Failures That Matter in AI Agent Systems
  • More Tests, More Confidence? Test Suites Are Investment Portfolios

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook