不,這是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;
};
}
它可能不是你自己的代碼在一個集合的存在意味着什麼,如果你期望他們不在另一個。
這幾乎與我使用的代碼相同。這有點麻煩。 'Condition'與Hamcrest'Matcher'非常相似;不同之處在於Hamcrest帶來了數十個(因爲畢竟是Hamcrest的概念)。此外,Hamcrest匹配器非常多才多藝,它們可以用於任何事情並可以通過。這是代碼完成必須支付的代價。也許有可能使用Hamcrest匹配器來代替條件? – 2014-11-07 07:31:21
我同意代碼繁瑣。 我在考慮允許重複使用hamcrest匹配器來代替Condition,我有點不情願,因爲它是一種不同的方法,我不是一個很大的粉絲,因爲我發現很難發現什麼是正確的macther,但是在像你的這是一個很好的解決方案。 – 2014-11-08 00:28:25