Testing a method that takes a lambda as a parameter can be accomplished by passing different lambdas to this method. For example, let's assume that we have the following functional interface:
@FunctionalInterface
public interface Replacer<String> {
String replace(String s);
}
Let's also assume that we have a method that takes lambdas of the String -> String type, as follows:
public static List<String> replace(
List<String> list, Replacer<String> r) {
List<String> result = new ArrayList<>();
for (String s: list) {
result.add(r.replace(s));
}
return result;
}
now, how can i write a JUnit test for this method using two lambdas ?
CodePudding user response:
@Test
public void testReplacer() throws Exception {
List<String> names = Arrays.asList(
"Ann a 15", "Mir el 28", "D oru 33");
List<String> resultWs = replace(
names, (String s) -> s.replaceAll("\\s", ""));
List<String> resultNr = replace(
names, (String s) -> s.replaceAll("\\d", ""));
assertEquals(Arrays.asList(
"Anna15", "Mirel28", "Doru33"), resultWs);
assertEquals(Arrays.asList(
"Ann a ", "Mir el ", "D oru "), resultNr);
}