您可以创建自己的特定匹配器,例如:
class ListMatcher { public static Matcher<List<Integer>> hasAtLeastItemsGreaterThan(final int targetCount, final int lowerLimit) { return new TypeSafeMatcher<List<Integer>>() { @Override public void describeTo(final Description description) { description.appendText("should have at least " + targetCount + " items greater than " + lowerLimit); } @Override public void describeMismatchSafely(final List<Integer> arg0, final Description mismatchDescription) { mismatchDescription.appendText("was ").appendValue(arg0.toString()); } @Override protected boolean matchesSafely(List<Integer> values) { int actualCount = 0; for (int value : values) { if (value > lowerLimit) { actualCount++; } } return actualCount >= targetCount; } };}}
然后像这样使用它:
public class ListMatcherTests {@Testpublic void testListMatcherPasses() { List<Integer> underTest = Arrays.asList(1, 10, 20); assertThat(underTest, ListMatcher.hasAtLeastItemsGreaterThan(2, 5));}@Testpublic void testListMatcherFails() { List<Integer> underTest = Arrays.asList(1, 10, 20); assertThat(underTest, ListMatcher.hasAtLeastItemsGreaterThan(2, 15));}
当然,这需要一些工作。而且不是很通用。但这有效。
另外,您可以在特定的测试方法中简单地“迭代”您的列表。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)