Last active
December 20, 2015 03:29
-
-
Save rafarocha/6064186 to your computer and use it in GitHub Desktop.
Exemplo de teste utilizando hamcrest e guava para obter apenas os números pares
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| @Test public void testFilterWithPredicatePairNumbers() { | |
| final List<Integer> numbers = getNumbers(); | |
| final List<Integer> onlyPair = filter(numbers, new Predicate<Integer>() { | |
| public boolean apply(Integer input) { | |
| return input % 2 == 0; | |
| } | |
| }); | |
| assertThat("deveriam vir apenas os numeros pares entre [0-10]", | |
| onlyPair, are(2, 4, 6, 8, 10) ); | |
| } | |
| private List<Integer> getNumbers() { | |
| Integer[] array = new Integer[10]; | |
| for (int i = 0; i < array.length; i++) { | |
| array[i] = i + 1; | |
| } | |
| return Lists.newArrayList( array ); | |
| } | |
| private List<Integer> filter(List<Integer> numeros, Predicate<Integer> predicate) { | |
| List<Integer> list = Lists.newArrayList(); | |
| for (Integer numero : numeros) { | |
| if ( predicate.apply(numero) ) { | |
| list.add( numero ); | |
| } | |
| } | |
| return list; | |
| } | |
| public static <T> Matcher<List<? super T>> are(final T... ts) { | |
| final Collection<?> c1 = Arrays.asList(ts); | |
| return new BaseMatcher<List<? super T>>() { | |
| public boolean matches(Object o) { | |
| Collection<?> c2 = (Collection<?>) o; | |
| return c1.containsAll(c2) && c2.containsAll(c1); | |
| } | |
| public void describeTo(Description description) { | |
| description.appendText("elements: "); | |
| description.appendValueList("(", ",", ")", ts); | |
| } | |
| }; | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
depências maven que utilizei. usei a versão 11.0.2 do guava devido a estar em projeto com java sdk 1.5