2014-11-04 72 views
6

中的任何一個事物持有或另一個持有我正在將一些測試從Hamcrest轉換爲AssertJ。在Hamcrest中,我使用下面的代碼片段:測試AssertJ

assertThat(list, either(contains(Tags.SWEETS, Tags.HIGH)) 
    .or(contains(Tags.SOUPS, Tags.RED))); 

也就是說,列表可能是那個或那個。我怎樣才能在AssertJ中表達這一點? anyOf函數(當然,任何是不是,但這將是第二個問題)需要Condition;我自己實現了這一點,但感覺這應該是一個普遍的情況。

回答

4

不,這是Hamcrest比AssertJ好的地方。

中寫入以下斷言:

Set<String> goodTags = newLinkedHashSet("Fine", "Good"); 
Set<String> badTags = newLinkedHashSet("Bad!", "Awful"); 
Set<String> tags = newLinkedHashSet("Fine", "Good", "Ok", "?"); 

// contains is statically imported from ContainsCondition 
// anyOf succeeds if one of the conditions is met (logical 'or') 
assertThat(tags).has(anyOf(contains(goodTags), contains(badTags))); 

您需要創建此條件:

import static org.assertj.core.util.Lists.newArrayList;  
import java.util.Collection;  
import org.assertj.core.api.Condition; 

public class ContainsCondition extends Condition<Iterable<String>> { 
    private Collection<String> collection; 

    public ContainsCondition(Iterable<String> values) { 
    super("contains " + values); 
    this.collection = newArrayList(values); 
    } 

    static ContainsCondition contains(Collection<String> set) { 
    return new ContainsCondition(set); 
    } 

    @Override 
    public boolean matches(Iterable<String> actual) { 
    Collection<String> values = newArrayList(actual); 
    for (String string : collection) { 
     if (!values.contains(string)) return false; 
    } 
    return true; 
    }; 
} 

它可能不是你自己的代碼在一個集合的存在意味着什麼,如果你期望他們不在另一個。

+0

這幾乎與我使用的代碼相同。這有點麻煩。 'Condition'與Hamcrest'Matcher'非常相似;不同之處在於Hamcrest帶來了數十個(因爲畢竟是Hamcrest的概念)。此外,Hamcrest匹配器非常多才多藝,它們可以用於任何事情並可以通過。這是代碼完成必須支付的代價。也許有可能使用Hamcrest匹配器來代替條件? – 2014-11-07 07:31:21

+1

我同意代碼繁瑣。 我在考慮允許重複使用hamcrest匹配器來代替Condition,我有點不情願,因爲它是一種不同的方法,我不是一個很大的粉絲,因爲我發現很難發現什麼是正確的macther,但是在像你的這是一個很好的解決方案。 – 2014-11-08 00:28:25

2

受此線程的啓發,您可能希望使用這個little repo我放在一起,它將Hamcrest Matcher API調整爲AssertJ的Condition API。還包括一個便捷的轉換外殼腳本。

+0

看起來很有希望。我會試一試。 – 2015-04-20 12:10:26