java - 如何为下面的java代码编写测试用例
问题描述
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;
}
解决方案
我会使用小而简单的数据,例如
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);
然后你可以用Map#size
, Map#containsKey
(需要null
-key)和...get("1").equals(1)
.
但是正如我在评论中提到的那样,如果您的函数可能为不同的值产生相同的键,那么您只有最后一个值,例如Function<Integer, Integer> toKey = i -> i%2
只会产生0
或1
作为键(和NullPointerException
for -values null
),因此List<Integer> values = Arrays.asList(1, 3)
将产生一个Map
只有一个条目"1" -> 3
.
推荐阅读
- kubernetes - GKE 集群升级到 1.14.6 后,VPN 访问内部网络无法正常工作
- networking - 在充当接入点的同时连接到 wifi 网络
- mongodb - 保存模型时缺失值
- c# - 比较使用反射的 2 种组装方法
- python - 如何测试使用上下文参数的 Flask API
- google-cloud-platform - 您可以在 BigQuery 的 DDL 语句中为视图指定列描述吗?
- java - TextView 没有被放置在屏幕的一半以下
- python - 当明确给出 s3 路径时,模式合并不起作用
- powershell - 从 PowerShell 对象输出中消除空行
- java - 带有两个分隔符的 Java 打印数组