使模拟方法返回传递给它的参数 [英] Making a mocked method return an argument that was passed to it

查看:82
本文介绍了使模拟方法返回传递给它的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑如下方法签名:

public String myFunction(String abc);

Mockito可以帮助返回该方法收到的相同字符串吗?

Can Mockito help return the same string that the method received?

推荐答案

您可以在Mockito中创建答案.假设我们有一个名为Application的接口,该接口带有方法myFunction.

You can create an Answer in Mockito. Let's assume, we have an interface named Application with a method myFunction.

public interface Application {
  public String myFunction(String abc);
}

以下是带有Mockito答案的测试方法:

Here is the test method with a Mockito answer:

public void testMyFunction() throws Exception {
  Application mock = mock(Application.class);
  when(mock.myFunction(anyString())).thenAnswer(new Answer<String>() {
    @Override
    public String answer(InvocationOnMock invocation) throws Throwable {
      Object[] args = invocation.getArguments();
      return (String) args[0];
    }
  });

  assertEquals("someString",mock.myFunction("someString"));
  assertEquals("anotherString",mock.myFunction("anotherString"));
}

从Mockito 1.9.5和Java 8开始,您还可以使用lambda表达式:

Since Mockito 1.9.5 and Java 8, you can also use a lambda expression:

when(myMock.myFunction(anyString())).thenAnswer(i -> i.getArguments()[0]);

这篇关于使模拟方法返回传递给它的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆