2016-06-14 52 views
1

我想檢查時,模擬是帶一個realtimeUpdatecurrentTime字段等於一些LocalDateTime我怎樣稱呼自定義的Hamcrest匹配器?

我想運行這樣的代碼使用自定義匹配:

verify(mockServerApi).sendUpdate(new TimeMatcher().isTimeEqual(update, localDateTime2)); 

,但我有一個編譯錯誤時我嘗試運行這個自定義匹配器。

我該如何解決這個問題?

public class TimeMatcher { 

    public Matcher<RealtimeUpdate> isTimeEqual(RealtimeUpdate realtimeUpdate, final LocalDateTime localDateTime) { 
     return new BaseMatcher<RealtimeUpdate>() { 
      @Override 
      public boolean matches(final Object item) { 
       final RealtimeUpdate realtimeUpdate = (RealtimeUpdate) item; 
       return realtimeUpdate.currentTime.equalTo(localDateTime); 
      } 

這是方法簽名

void sendRealTimeUpdate(RealtimeUpdate realtimeUpdate); 

,這是編譯錯誤:

enter image description here

+0

http://www.planetgeek.ch/2012/03/07/create-your-own-match er/ –

回答

1

這裏是你如何能繼續

TimeMatcher,你只需要LocalDateTime

public class TimeMatcher { 
    public static Matcher<RealtimeUpdate> isTimeEqual(final LocalDateTime localDateTime) { 
     return new BaseMatcher<RealtimeUpdate>() { 
      @Override 
      public void describeTo(final Description description) { 
       description.appendText("Date doesn't match with "+ localDateTime); 
      } 

      @Override 
      public boolean matches(final Object item) { 
       final RealtimeUpdate realtimeUpdate = (RealtimeUpdate) item; 
       return realtimeUpdate.currentTime.isEqual(localDateTime); 
      } 
     }; 
    } 
} 

測試:

Mockito.verify(mockRoutingServerApi).sendRealTimeUpdate(
    new ThreadSafeMockingProgress().getArgumentMatcherStorage() 
     .reportMatcher(TimeMatcher.isTimeEqual(localDateTime2)) 
     .returnFor(RealtimeUpdate.class)); 

您需要使用returnFor提供的參數類型,爲RealtimeUpdate由預期sendRealTimeUpdate

這相當於:

Mockito.verify(mockRoutingServerApi).sendRealTimeUpdate(
    Matchers.argThat(TimeMatcher.isTimeEqual(localDateTime2)) 
); 
+0

請注意,'sendRealTimeUpdate(RealtimeUpdate realtimeUpdate)'而不是'localDateTime2'作爲參數 –

+0

再次固定檢查 –

+0

'您需要使用returnFor來返回類型對象,即使我只想驗證參數send方法調用?我現在不想重寫一個方法,只需確認它是用一個特定的參數來調用。 –

相關問題