2012-04-06 23 views

回答

1

這可行,但我不高興,它需要這麼多的代碼來取代簡單的循環。 我比「選擇」更喜歡「過濾器」,因爲它使代碼更簡單,並且我認爲更容易閱讀。

public Collection<String> search(String regex) { 
    List<String> matches = filter(matches(regex), dictionary); 
    return matches; 
    } 

    static class MatchesMatcher extends TypeSafeMatcher<String> { 

    private String regex; 

    MatchesMatcher(String regex) { 
     this.regex = regex; 
    } 

    @Override 
    public boolean matchesSafely(String string) { 
     return string.matches(regex); 
    } 

    public void describeTo(Description description) { 
     description.appendText("matches " + regex); 
    } 

    } 

    @Factory 
    public static Matcher<String> matches(String regex) { 
    return new MatchesMatcher(regex); 
    } 
+1

那麼,它需要很多代碼*一次*。我在單元測試庫中添加了一個正則表達式匹配器,所以我不必再次編寫它。如果我在生產代碼中使用匹配器,我只需將正則表達式匹配器移動到適當的庫。正如我的回答中所指出的那樣,我希望看到這個匹配器在一個隨時可用的公共圖書館中。 – 2012-04-11 19:08:40

1

如果要篩選集合,你可以做如下所述:

@Test 
public void test() { 
    Collection<String> collection = new ArrayList<String>(); 
    collection.add("foo"); 
    collection.add("bar"); 
    collection.add("foo"); 

    List<String> filtered = select(collection, having(on(String.class), equalTo("foo"))); 
    assertEquals(2, filtered.size()); 
} 
+0

謝謝...我想我仍然不相信1.語法是如此詳細,2。我必須寫我自己的匹配來引導,因爲似乎是在hamcrest沒有正則表達式匹配。 – wytten 2012-04-06 14:25:07

2

如果有可能使用having(on(...))結構去做,調用看起來是這樣的:

select(collection, having(on(String.class).matches("f*"))) 

但不幸的是,這是不可能的,因爲String類是final的,所以on(String.class)無法創建having匹配器所需的代理。

儘管hamcrest不帶正則表達式匹配器,你不必自己寫。該網提供了幾個實現。我希望看到這樣的匹配器在一個隨時可用的公共庫中,我可以簡單地將它包含爲依賴關係,而不必複製源代碼。