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
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • IntelliJ Integration for Mockito
  • Effective Engineering Feedback: Software Testing
  • The LLM Selection War Story: Part 2 - The Six LLM Failure Archetypes That Will Wreck Your Production System
  • Agentic Development: My Invisible Dev Team

Trending

  • Your AI Agent Tests Are Passing, But Your Agent Is Still Broken
  • RAG Is Not Enough: Advanced Retrieval Architectures Using Vertex AI Search on GCP
  • When Perfect Data Breaks: The Journey from Data Quality to Data Observability
  • Ujorm3: A New Lightweight ORM for JavaBeans and Records
  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ğ user avatar
Hakan Altındağ
·
Dec. 15, 20 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
39.0K Views

Join the DZone community and get the full member experience.

Join For Free

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
  • Effective Engineering Feedback: Software Testing
  • The LLM Selection War Story: Part 2 - The Six LLM Failure Archetypes That Will Wreck Your Production System
  • Agentic Development: My Invisible Dev Team

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • 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