Reputation: 101
I am trying to mock the below line but it gives an error while executing it, it says:
Misplaced argument matcher detected here:
You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
when(mock.get(anyInt())).thenReturn(null);
doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());
verify(mock).someMethod(contains("foo"))
Also, this error might show up because you use argument matchers with methods that cannot be mocked. Following methods cannot be stubbed/verified: final/private/equals()/hashCode().
org.mockito.exceptions.misusing.InvalidUseOfMatchersException: The line of code is:
PowerMockito.mockStatic(NameOfClass.class);
expect( NameOfClass.nameOfMethod((URL)Mockito.any(),Mockito.anyString())).andReturn(actualOutput);
the class is somewhat like this:
public class SomeClass {
public static String method(String URL, String str) {
//functioning
return "";
}
}
How can I mock it?
Upvotes: 0
Views: 7432
Reputation: 15634
i can't change things in my code.....it's an old code and getting used at many places – NealGul
Instead of using Powermock:
There are 3 easy, quick and safe steps:
create a non-static copy of that method (with a new name):
class StaticMethodRefactoring {
static int staticMethod(int b) {
return b;
}
int nonStaticMethod(int b) {
return b;
}
}
let the static version call the non-static version:
class StaticMethodRefactoring {
static int staticMethod(int b) {
return new StaticMethodRefactoring(). nonStaticMethod(b);
}
int nonStaticMethod(int b) {
return b;
}
}
use your IDE's inline Method refactoring to replace the static access with the non-static.
Most likely there is an option to delete the old static version of the method. If some other projects use this static method you may which to keep it...
Your IDE also provides the inline method feature at the place where you access the static method. This way you can change to non-static access step by step as needed.
That's it!
In all open projects in your current IDE session any access to the static method is replaced. Now you can change your class under test to get the instance injected via constructor or any other DI-mechanism and replace is for the tests with a simple mockito-mock...
Upvotes: 1
Reputation: 427
You can use PowerMockito on top of Mockito. Something like this:
PowerMockito.mockStatic(NameOfClass.class);
expect( NameOfClass.nameOfMethod((URL)Mockito.any(),Mockito.anyString())).andReturn(actualOutput);
Upvotes: 1