2013-06-26 44 views
0

如下圖所示,我要檢查mock.fireEvent()被調用特定事件(事件2此處)如何匹配模擬上的第二個調用?

mock.fireEvent(event1); 

mock.fireEvent(event2); 

verify(mock).fireEvent(matcherToCheckTheFieldOfEvent2); 

,但得到指示

verify(mock).fireEvent(matcherToCheckTheFieldOfEvent2); 

首先嚐試匹配錯誤調用

mock.fireEvent(argThat(event1)); 

問題是如何讓event2匹配?

匹配器看起來是這樣的:

private class IsEvent2 extends ArgumentMatcher<Event2> 
    { 
     @Override 
     public boolean matches(Object arg) 
     { 
       return ((Event2) arg).methodGotCalled(); 
     } 
    } 
+0

能否請您加入確切的錯誤信息你得到?添加更多的junit測試代碼也會有所幫助。 – Alban

+0

完整的測試代碼相當多,主要理念是捕獲事件的類型是Event1,並且不能將其轉換爲Event2,並添加Matcher代碼 –

回答

0

這是老線,但我得到了這個問題最近,通過使用ArgumentCaptor捕捉觸發的事件的列表,並斷言預期的事件解決它存在於名單。然後

ArgumentCaptor<SomeEvent> argument = ArgumentCaptor.forClass(SomeEvent.class); 
verify(mock, times(2)).fire(argument.capture()); 

argument將捕獲的事件列表,並可以單獨地斷言他們

assertThat(argument.getAllValues(), hasItems(
    new SomeEventMatcher(event1), 
    new SomeEventMatcher(event2) 
)); 

而且匹配是這樣的:

static class SomeEventMatcher extends ArgumentMatcher<SomeEvent> { 
    private SomeEvent expected; 

    public SomeEventMatcher(SomeEvent expected) { 
     this.expected = expected; 
    } 

    @Override 
    public boolean matches(Object argument) { 
     if (argument == null) { 
      return false; 
     } 
     else { 
      SomeEvent event = (SomeEvent) argument; 
      // the fields that you want to compare with the matcher 
      return new EqualsBuilder() 
        .append(expected.getField1(), event.getField1()) 
        .append(expected.getField2(), event.getField2()) 
        .build(); 
     } 
    } 
} 
相關問題