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.
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.
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.
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; } }
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());
Notice that the getInt() method is not explicitly stubbed. It will use the default behavior of returning 0.
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!