PowerMockito.whenNew()
There are some cases where source code directly create a new instance of object without any injection mechanism. JVM will create an instance with actual class with actual methods. For these cases, we can use PowerMockito.whenNew()
method to
Similar to Mockito's when()
statement, we can tell PowerMock to inject our mock instead of creating new instance of real object.
Here is an example:
In above example, CustomClass instance is created without any mechanism to inject it, lets see how can we tell PowerMockito to inject our mock.
Note: keep in mind, if you need to manipulate behavior (byte code) of any class, as we are doing in case of whenNew()
method, we need to add ExampleClass.class
in @PrepareForTest
.
Note Keep in mind, whenNew()
will not work when new instance was created inside a nested scope.
Last updated