2016-12-02 24 views
4

試圖用2個可能的調用/返回路徑使用自定義匹配器來存根類...遇到了一個興趣問題。Mockito作爲調用計數存根

下面是測試我寫的說明...

這可能是難以實現的,但我本來期望第一ArgumentMatcher磕碰第二when(...).thenReturn(...)

但在運行代碼時不會被調用在標準輸出上打印foobar。有什麼我們可以做,以防止這種行爲?還是我使用了錯誤的方式試圖通過存根與多個自定義ArgumentMatcher

FYI一個模擬 - powermock是在我的類路徑中的其他測試(不知道這事,但我看到它的堆棧跟蹤)

import org.junit.Test; 
import org.mockito.ArgumentMatcher; 

import java.io.File; 
import java.io.FilenameFilter; 

import static org.mockito.Matchers.*; 
import static org.mockito.Mockito.mock; 
import static org.mockito.Mockito.when; 

public class MyTest { 
    @Test 
    public void name() throws Exception { 
     File file = mock(File.class); 
     when(file.list(argThat(new ArgumentMatcher<FilenameFilter>() { 
      @Override 
      public boolean matches(Object argument) { 
       System.out.println("foobar"); 
       return 1 + 1 >2; 
      } 
     }))).thenReturn(null); 
     // at this point, mockito will attempt to run the previous matcher, treating this stub code as invocation ... and printing out 'foobar' 
     when(file.list(argThat(new ArgumentMatcher<FilenameFilter>() { 
      @Override 
      public boolean matches(Object argument) { 
       System.out.println("barbar"); 
       return true; 
      } 
     }))).thenReturn(null); 

    } 
} 

編輯添加了註釋,以幫助說明

回答

4

如果使用doReturn()語法,則該方法不被調用。

doReturn(null).when(file).list(argThat(new ArgumentMatcher<FilenameFilter>() { 
    @Override 
    public boolean matches(Object argument) { 
     System.out.println("barbar"); 
     return true; 
    } 
})); 

有關更多詳細信息,請參閱this answer。此外,the docs解釋這個用例(重點煤礦):

您可以使用doReturn(),[...]代替調用相應的有()時,對於任何方法。這是必要的,當你:

  • 存根void的方法
  • 刺探的對象存根方法(見下文)
  • 存根相同的方法不止一次,以改變在中間的模仿行爲一個測試。
+1

謝謝你的 – echen

相關問題