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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • IntelliJ Integration for Mockito
  • How to Unit Test Classes Which Create New Objects
  • How to Migrate From JUnit 4 to JUnit 5 Step by Step
  • Beginners Guide to Mocking in Scala

Trending

  • Agentic AI for Automated Application Security and Vulnerability Management
  • From Zero to Production: Best Practices for Scaling LLMs in the Enterprise
  • Beyond ChatGPT, AI Reasoning 2.0: Engineering AI Models With Human-Like Reasoning
  • How to Practice TDD With Kotlin
  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
37.8K 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
  • How to Unit Test Classes Which Create New Objects
  • How to Migrate From JUnit 4 to JUnit 5 Step by Step
  • Beginners Guide to Mocking in Scala

Partner Resources

×

Comments
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!