Mock method with parameters

ⅰ亾dé卋堺 提交于 2021-02-08 11:43:39

问题


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?


回答1:


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);



回答2:


i can't change things in my code.....it's an old code and getting used at many places – NealGul

Instead of using Powermock:

how to convert a static method into a non-static when it is referenced at many places in the codebase?

There are 3 easy, quick and safe steps:

  1. 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;
        }
    }
    
  2. 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;
        }
    }
    
  3. 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...



来源:https://stackoverflow.com/questions/44062928/mock-method-with-parameters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!