考虑如下方法签名:

public String myFunction(String abc);

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


当前回答

这有点老了,但我来这里是因为我有同样的问题。我使用JUnit,但这次是在Kotlin应用程序中使用mock。我在这里发布了一个示例,以供参考,并与Java同行进行比较:

@Test
fun demo() {
  // mock a sample function
  val aMock: (String) -> (String) = mockk()

  // make it return the same as the argument on every invocation
  every {
    aMock.invoke(any())
  } answers {
    firstArg()
  }

  // test it
  assertEquals("senko", aMock.invoke("senko"))
  assertEquals("senko1", aMock.invoke("senko1"))
  assertNotEquals("not a senko", aMock.invoke("senko"))
}

其他回答

使用Java 8,即使使用旧版本的Mockito,也可以创建一个单行答案:

when(myMock.myFunction(anyString()).then(i -> i.getArgumentAt(0, String.class));

当然,这并不像大卫·华莱士(David Wallace)建议的使用AdditionalAnswers那样有用,但如果您想“动态”转换论点,这可能会有用。

您可能希望将verify()与ArgumentCaptor结合使用,以确保测试中的执行,并使用ArgumentCaptor评估参数:

ArgumentCaptor<String> argument = ArgumentCaptor.forClass(String.class);
verify(mock).myFunction(argument.capture());
assertEquals("the expected value here", argument.getValue());

显然,可以通过argument.getValue()访问参数的值,以进行进一步的操作/检查/其他操作。

如果您有Mockito 1.9.5或更高版本,有一种新的静态方法可以为您创建Answer对象。你需要写一些像

import static org.mockito.Mockito.when;
import static org.mockito.AdditionalAnswers.returnsFirstArg;

when(myMock.myFunction(anyString())).then(returnsFirstArg());

或替代地

doAnswer(returnsFirstArg()).when(myMock).myFunction(anyString());

注意,returnsFirstArg()方法在AdditionalAnswers类中是静态的,这是Mockito 1.9.5的新特性;所以您需要正确的静态导入。

使用Java 8,Steve的答案可以变成

public void testMyFunction() throws Exception {
    Application mock = mock(Application.class);
    when(mock.myFunction(anyString())).thenAnswer(
    invocation -> {
        Object[] args = invocation.getArguments();
        return args[0];
    });

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

编辑:更短:

public void testMyFunction() throws Exception {
    Application mock = mock(Application.class);
    when(mock.myFunction(anyString())).thenAnswer(
        invocation -> invocation.getArgument(0));

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

这有点老了,但我来这里是因为我有同样的问题。我使用JUnit,但这次是在Kotlin应用程序中使用mock。我在这里发布了一个示例,以供参考,并与Java同行进行比较:

@Test
fun demo() {
  // mock a sample function
  val aMock: (String) -> (String) = mockk()

  // make it return the same as the argument on every invocation
  every {
    aMock.invoke(any())
  } answers {
    firstArg()
  }

  // test it
  assertEquals("senko", aMock.invoke("senko"))
  assertEquals("senko1", aMock.invoke("senko1"))
  assertNotEquals("not a senko", aMock.invoke("senko"))
}