Java 修改 void 函数的输入参数,然后读取它

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27421417/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 04:21:54  来源:igfitidea点击:

Modify input parameter of a void function and read it afterwards

javajunitmockingmockito

提问by Juan

I have a rather complex java function that I want to test using jUnit and I am using Mockito for this purpose. This function looks something like this:

我有一个相当复杂的 java 函数,我想使用 jUnit 进行测试,为此我正在使用 Mockito。这个函数看起来像这样:

public void myFunction (Object parameter){
   ...
   doStuff();
   ...
   convert(input,output);
   ...
   parameter.setInformationFrom(output);
}

The function convert sets the attributes of output depending on input and it's a void type function, although the "output" parameter is what is being used as if it were returned by the function. This convert function is what I want to mock up as I don't need to depend on the input for the test, but I don't know how to do this, as I am not very familiar with Mockito.

函数 convert 根据输入设置输出的属性,它是一个 void 类型的函数,尽管“输出”参数是被使用的,就好像它是由函数返回的一样。这个转换函数是我想要模拟的,因为我不需要依赖于测试的输入,但我不知道如何做到这一点,因为我对 Mockito 不是很熟悉。

I have seen basic cases as when(something).thenReturn(somethingElse)or the doAnswer method which I understand is similar to the previous one but more logic can be added to it, but I don't think these cases are appropriate for my case, as my function does not have a return statement.

我已经看到了基本情况,when(something).thenReturn(somethingElse)或者我理解的 doAnswer 方法与前一个类似,但可以向其中添加更多逻辑,但我认为这些情况不适合我的情况,因为我的函数没有返回陈述。

采纳答案by Jeff Bowman

If you want the mocked method to call a method on (or otherwise alter) a parameter, you'll need to write an Answer as in this question ("How to mock a void return method affecting an object").

如果您希望被模拟的方法调用(或以其他方式更改)参数的方法,则需要编写一个答案,如本问题(“如何模拟影响对象的 void 返回方法”)。

From Kevin Welker's answerthere:

来自Kevin Welker回答

doAnswer(new Answer() {
    Object answer(InvocationOnMock invocation) {
        Object[] args = invocation.getArguments();
        ((MyClass)args[0]).myClassSetMyField(NEW_VALUE);
        return null; // void method, so return null
    }
}).when(mock).someMethod();

Note that newer best-practices would have a type parameter for Answer, as in Answer<Void>, and that Java 8's lambdas can compress the syntax further. For example:

请注意,较新的最佳实践将为 Answer 提供一个类型参数,如 中所示Answer<Void>,并且 Java 8 的 lambda 表达式可以进一步压缩语法。例如:

doAnswer(invocation -> {
  Object[] args = invocation.getArguments();
  ((MyClass)args[0]).myClassSetMyField(NEW_VALUE);
  return null; // void method in a block-style lambda, so return null
}).when(mock).someMethod();