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

2022-01-14 00:00:00 mocking mockito java junit

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

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:

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

convert 函数根据输入设置输出的属性,它是一个 void 类型的函数,尽管输出"是参数是正在使用的,就好像它是由函数返回的一样.这个转换函数是我想要模拟的,因为我不需要依赖于测试的输入,但我不知道该怎么做,因为我对 Mockito 不是很熟悉.

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.

我见过的基本情况是 when(something).thenReturn(somethingElse)或我理解的 doAnswer 方法与前一个方法类似,但可以添加更多逻辑,但我认为这些情况不适合我的情况,因为我的函数没有返回语句.

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.

推荐答案

如果您希望模拟方法在(或以其他方式更改)参数上调用方法,您需要像这个问题一样写一个答案(如何模拟影响对象的 void 返回方法").

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").

来自 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();

请注意,较新的最佳实践将具有 Answer 的类型参数,如 Answer,并且 Java 8 的 lambda 可以进一步压缩语法.例如:

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:

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

相关文章