Ravitosh Khatri
Ravitosh Khatri

Reputation: 13

How to write test case for below java code

public class CollectionUtils {
    public static <K, V> Map<K, V> createMap(Iterable<V> values, Function<V, K> keyFunction, boolean skipNullKeys) {
        Map<K, V> map = new HashMap<>();
        for (V value : values) {
            K key = keyFunction.apply(value);
            if (key != null || !skipNullKeys) {
                map.put(key, value);
            }
        }
        return map;
    }

Upvotes: 0

Views: 43

Answers (1)

Stefan Warminski
Stefan Warminski

Reputation: 1845

I would use small and simple data, e. g.

List<Integer> values = Arrays.asList(1, null);
Function<Integer, String> toKey = String::valueOf;
Map<String, Integer> withNull = createMap(values, toKey, false);
Map<String, Integer> noNull = createMap(values, toKey, true);

Then you can test with Map#size, Map#containsKey (needed for null-key) and ...get("1").equals(1).

But as I mentioned in the comment, if your function may result in the same key for different values you only have the last value, e. g. Function<Integer, Integer> toKey = i -> i%2 will only procude 0 or 1 as a key (and a NullPointerException for null-values) so List<Integer> values = Arrays.asList(1, 3) will produce a Map with only one entry "1" -> 3.

Upvotes: 1

Related Questions