Mockito: Passing in any() and a literal to the same method

Mockito has a restriction where when using Mockito.when(someMethod(...)) you can’t pass in a combination of any() and literal values to someMethod().It complains that we have to pick one. So, the following is illegal:

Solution 1 (preferred and as shown by Stephen):

Mockito.when(context.configFileProvider(eq(“file1”), any())).thenReturn(“file1_contents”)

Solution 2 (works but ugly and the original post here):

Mockito.when(context.configFileProvider("file1", any())).thenReturn("file1_contents")

There is a way around it which I stumbled upon when trying to test nested closures while writing Groovy scripts for Jenkins (don’t ask me). Here it is:

    Mockito.when(context.configFileProvider(Mockito.any(), Mockito.any())).thenAnswer(
        new Answer<String>(){
            @Override
            String answer(InvocationOnMock invocation){
                List arg1 = invocation.getArgument(0)
                switch (arg1.get(0)) {
                    case "file1": return "file1_contents"
                }
            }
        }
    );

This is logically equivalent to the previous statement.

原文链接:Mockito: Passing in any() and a literal to the same method

© 版权声明
THE END
喜欢就支持一下吧
点赞6 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容