使模擬方法返回傳遞給它的參數

考慮以下方法簽名: ide

public String myFunction(String abc);

Mockito能夠幫助返回該方法收到的相同字符串嗎? 函數


#1樓

若是您具備Mockito 1.9.5或更高版本,則有一個新的靜態方法能夠爲您建立Answer對象。 你須要寫一些像 測試

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

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

或者 spa

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

注意, returnsFirstArg()方法在AdditionalAnswers類中是靜態的,它是Mockito 1.9.5的新增功能。 所以您須要正確的靜態導入。 code


#2樓

您能夠在Mockito中建立答案。 假設咱們有一個名爲Application的接口,該接口帶有方法myFunction。 對象

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

這是帶有Mockito答案的測試方法: 接口

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函數提供了一種更簡單的方法: 字符串

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


#3樓

使用Java 8,即便使用舊版本的Mockito,也能夠建立單行答案: it

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

固然,這不如使用David Wallace建議的AdditionalAnswers有用,可是若是您想「即時」轉換參數,則可能有用。


#4樓

使用Java 8, 史蒂夫的答案能夠變成

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"));
}

#5樓

您可能但願將verify()與ArgumentCaptor結合使用以確保在測試中執行,而ArgumentCaptor能夠評估參數:

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

參數的值顯然能夠經過arguments.getValue()進行訪問,以進行進一步的操做/檢查/不管如何。

相關文章
相關標籤/搜索