Home > Java > javaTutorial > How to Mock a Single Static Method and Return a Custom Object Using PowerMock?

How to Mock a Single Static Method and Return a Custom Object Using PowerMock?

Mary-Kate Olsen
Release: 2024-12-09 20:33:18
Original
428 people have browsed it

How to Mock a Single Static Method and Return a Custom Object Using PowerMock?

PowerMock: Mocking a Single Static Method to Return an Object

When mocking static methods in Java, you may encounter the need to selectively stub a specific method and return a custom object. PowerMock provides the necessary functionality to achieve this.

Enabling Static Mocking

To mock static methods, you first need to enable static mocking for the target class using PowerMockito.mockStatic(). However, the default answer strategy assigned to this method can lead to type mismatch errors if the class contains multiple static methods with different return types.

Mocking and Stubbing

Instead, you should use the one-argument overload of mockStatic() to enable static mocking, then use PowerMockito.when() and thenReturn() to specify the desired behavior for the individual method. This allows you to define custom return values for each stubbed method.

Example Usage

Consider a class with two static methods, one returning a String and the other an int:

class ClassWithStatics {
  public static String getString() {
    return "String";
  }

  public static int getInt() {
    return 1;
  }
}
Copy after login

To stub the getString() method to return "Hello!", you would do the following:

PowerMockito.mockStatic(ClassWithStatics.class);
when(ClassWithStatics.getString()).thenReturn("Hello!");
System.out.println("String: " + ClassWithStatics.getString());
Copy after login

Notice that the getInt() method is not explicitly stubbed. It will use the default behavior of returning 0.

Conclusion

By using the correct combination of static mocking and stubbing techniques, you can selectively mock a single static method and return an object in PowerMock. This enables you to test and isolate specific static method behavior in your Java code.

The above is the detailed content of How to Mock a Single Static Method and Return a Custom Object Using PowerMock?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template