How to Mock a Non-Static Method from Another Class in Java Unit Testing?

Question

How can I mock a non-static method of a different class while unit testing Java code?

Answer

Mocking non-static methods in Java unit testing can be challenging, especially when working with frameworks like Mockito. In this guide, we'll explore how to efficiently mock a non-static method from a different class using Mockito, enabling you to isolate the class under test and facilitate effective unit tests.

import static org.mockito.Mockito.*;
import org.junit.jupiter.api.*;
import org.mockito.InjectMocks;
import org.mockito.Mock;

class MyServiceTest {
    @Mock
    private ExternalService externalService;

    @InjectMocks
    private MyService myService;

    @BeforeEach
    void setUp() {
        MockitoAnnotations.openMocks(this);
    }

    @Test
    void testMyServiceMethod() {
        // Arrange
        when(externalService.nonStaticMethod(anyString())).thenReturn("Mocked Response");

        // Act
        String result = myService.myMethod();

        // Assert
        assertEquals("Expected Result", result);
    }
}

Causes

  • Non-static methods are bound to instances and are generally more complex to mock compared to static methods.
  • When testing, you often need to isolate the unit of work without merging dependencies.

Solutions

  • Use a mocking framework like Mockito which allows you to create mock objects and specify behavior for non-static methods.
  • Annotate the test class with @RunWith(MockitoJUnitRunner.class) to enable Mockito annotations if you're using JUnit 4, or @ExtendWith(MockitoExtension.class) for JUnit 5.
  • Create mock instances of the class containing the non-static method and define behavior using when() and thenReturn() methods.

Common Mistakes

Mistake: Forgetting to initialize mocks with MockitoAnnotations.openMocks(this) or using the correct runner.

Solution: Ensure you call MockitoAnnotations.openMocks() in the @BeforeEach setup method or use the appropriate test runner.

Mistake: Not verifying that the mocked method was called as expected.

Solution: Always include verification logic in your tests to confirm that the mocked methods were invoked with the right parameters.

Helpers

  • Java unit testing
  • mock non-static method
  • Mockito tutorial
  • unit testing best practices
  • Java testing frameworks

Related Questions

⦿How to Convert Joda-Time Period to Jadira UserType Persistent Period with Custom Format?

Learn how to convert JodaTime Period to Jadira UserType Persistent Period with a custom format in your Java applications.

⦿Is There a Native Library for Building an XMPP Client on Android?

Explore the available Android native libraries for developing XMPP clients including implementation details and common issues.

⦿How to Utilize SonarQube with Maven for Incremental Analysis Before Commits

Learn how to configure and use SonarQube with Maven for effective incremental analysis ahead of code commits.

⦿How to Resolve ClassNotFoundException When Using URLClassLoader to Load a Class from a File

Learn how to fix ClassNotFoundException in Java when loading classes with URLClassLoader including code snippets and common debugging tips.

⦿How to Customize Line Chart Colors Using Apache POI

Learn how to customize the colors of line charts in Apache POI for better data visualization in Excel spreadsheets.

⦿How to Use Local Fields of Thread Type in a Runnable Implementation

Learn how to effectively manage local Thread fields in a Runnable implementation with best practices and code examples.

⦿How to Implement Deterministic IV Construction for GCM in Java

Learn how to create a deterministic Initialization Vector IV for GaloisCounter Mode GCM in Java with examples best practices and debugging tips.

⦿How to Display All Fields in a Database Query?

Learn how to effectively display all fields in a database query with stepbystep examples and common mistakes to avoid.

⦿How Can I Retrieve a Time Zone Using Only a Country Name?

Learn how to get a time zone from a country name using programming methods in Python with expert insights and code examples.

⦿How to Resolve java.lang.ClassNotFoundException During WebLogic .ear Deployment

Learn how to troubleshoot java.lang.ClassNotFoundException when deploying .ear files in WebLogic. Stepbystep solutions and best practices included.

© Copyright 2025 - CodingTechRoom.com