java 使用 Mockito,如何在 void 方法上拦截回调对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3581754/
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-10-30 02:31:07  来源:igfitidea点击:

Using Mockito, how do I intercept a callback object on a void method?

javaunit-testingcallbackjaasmockito

提问by brasskazoo

I'm using mockito to test a legacy JAAS/LDAP login module.

我正在使用 mockito 来测试旧的 JAAS/LDAP 登录模块。

The javax.security.auth.callback.CallbackHandlerinterface defines the function:

javax.security.auth.callback.CallbackHandler接口定义了功能:

void handle(javax.security.auth.callback.Callback[] callbacks)

I'm expecting callbacksto contain a NameCallback, which is the object that needs to be manipulated to pass the test.

我期望callbacks包含一个NameCallback,它是需要被操纵以通过测试的对象。

Is there a way to mock this effectively, or would I be better off with a stubbed implementation of CallbackHandler?

有没有办法有效地模拟这个,或者我会更好地实现CallbackHandler?

回答by brasskazoo

For functions returning void, use doAnswer()

对于返回的函数void,使用doAnswer()

doAnswer(...).when(mockedObject).handle(any(Callback[].class));

And an Answerthat performs the interception must go in as the parameter to doAnswer, e.g. as an anonymous class:

Answer执行拦截的an必须作为 to 的参数进入doAnswer,例如作为匿名类:

new Answer() {
  public Object answer(InvocationOnMock invocation) {
      Object[] args = invocation.getArguments();
      Mock mock = invocation.getMock();
      return null;
  }}

In this case argswill be the array Callback[]!

在这种情况下args将是数组Callback[]