简体   繁体   English

使用Mockito:在私有静态方法中匹配多个参数?

[英]Using Mockito: Matching multiple arguments in a private static method?

I've been trying to use Mockito and PowerMockito to test my code. 我一直在尝试使用Mockito和PowerMockito来测试我的代码。 I have something akin to the following class: 我有类似于以下类的东西:

public class asdfClass{

    public static String methodToMock(String item, String otheritem){
      return "asdf";
    }

    public static String methodToMock(String item){
      return "asdf";    
    }
}

For whatever reason, though, running the following: 无论出于何种原因,运行以下内容:

PowerMockito.spy(asdfClass.class);

PowerMockito.when(asdfClass.methodToMock(Mockito.any())).thenReturn("asdfghj");

appears to compile correctly but running 似乎正确编译但正在运行

PowerMockito.spy(asdfClass.class);

PowerMockito.when(asdfClass.methodToMock(Mockito.any(), Mockito.any())).thenReturn("asdfghj");

does not and spits out a "'void' type not allowed here" error on the Mockito.any()s. 没有,并在Mockito.any()s上吐出一个“'void'类型不允许这里”错误。

Does anyone know what to do about this? 有谁知道怎么办? The only other result I saw on stackoverflow suggested that the reader take a look at the documentation, though I don't think it said anything about multiple arguments in a private static method. 我在stackoverflow上看到的唯一其他结果表明读者会看一下文档,尽管我认为它没有说明私有静态方法中的多个参数。

(In the end I'm hoping to mock a void result with a doNothing though I've boiled the issue I'm having down to the fact that all of my void methods take multiple arguments) (最后我希望用doNothing来模拟一个无效结果,虽然我已经解决了这个问题,我已经知道我的所有void方法都有多个参数)

EDIT: Never mind, got it: Is it possible to use partial mocking for private static methods in PowerMock? 编辑:没关系,得到它: 是否可以在PowerMock中使用部分模拟私有静态方法? (Comment 4 on the chosen answer). (关于所选答案的评论4)。 Curiously this didn't work before but that might've been a typo on my part for all I know) 奇怪的是,这之前没有用,但这可能是我所知道的所有错误)

As per Is it possible to use partial mocking for private static methods in PowerMock? 根据是否可以在PowerMock中对私有静态方法使用部分模拟? , PowerMockito.doReturn(mockData).when(DataProvider.class, "readFile", param1, param2, ...) does the trick. ,PowerMockito.doReturn(mockData).when(DataProvider.class,“readFile”,param1,param2,...)可以解决问题。

你模拟了void方法,所以它不能返回任何东西,所以应该省略thenReturn()语句(例如,而不是when() ,使用doNothing() )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM