2012-09-07 37 views
1

如何匹配來自Hamcrest的TestNG和hasItem的空集合?這是我通過一次測試得到的結果。用Hamcrest的hasItem匹配空集合()

java.lang.AssertionError: 
Expected: a collection containing email = null phone = null 
got: <[]> 

這裏是我的匹配類:

private static class MyPersonMatcher extends TypeSafeMatcher<Person> { 
    private final String email; 
    private final String phone; 
     public ContactAgentUsageMatcher() { 
    } 
    public ContactAgentUsageMatcher(String email, String phone, Integer listingId) { 
     this.email = email; 
     this.phone = phone; 
    } 
    @Override 
    public void describeTo(Description description) { 
     description.appendText("email = "); 
     description.appendValue(this.email); 
     description.appendText(" phone = "); 
     description.appendValue(this.phone); 
    } 
    @Override 
    public boolean matchesSafely(ContactAgentUsage contactAgentUsage) { 
     if ((this.email == null) && (this.phone == null)) { 
     return true; 
     } 
     else { 
     return ObjectUtils.equals(this.email, contactAgentUsage.getEmail()) 
      && ObjectUtils.equals(this.phone, contactAgentUsage.getPhone()); 
     } 
    } 
} 

失敗的試驗是

assertThat(argument.getAllValues(), hasItem(expectedMatcher)); 

其中expectedMatcher由數據提供商提供。因此我不確定要傳遞什麼來匹配這個「空集合」。我傳遞了默認的構造函數,但我知道這不起作用,因爲它創建了與null成員的集合。

這是我的數據提供程序的一部分:

{ new ContactAgentUsageMatcher()} 

回答

2

您的自定義匹配將匹配任何現有Person當配置emailname均設置爲null。但是,收集不包含的任何Person s以匹配。在這種情況下Hamcrest的hasItem(matcher)未通過測試,並且是用於空集合的錯誤匹配器。

這裏有兩種解決方法:

  1. 更改數據提供者和測試,以採取全面匹配,包括hasItem。對於上述情況,您可以通過emptyIterable。缺點是你需要告訴Java編譯器它應該使用哪個泛型,這會混亂測試。

  2. 創建第二個測試來處理產生空集合的數據集。