【发布时间】:2017-02-22 15:33:02
【问题描述】:
我对如何组织和测试如下代码存在概念上的疑问,其中对辅助方法的调用是类的所有公共方法的第一条指令。我的想法是让代码干净且可测试。
代码是一个示例,试图通过“缓存”类来说明这一点。这个类有一个可选的前缀,如果设置了,它将应用于缓存中的所有键。
import java.util.HashMap;
public class Cache {
private HashMap<String, Integer> inMemoryCache;
private String prefix;
public Cache() {
this.inMemoryCache = new HashMap<String, Integer>();
prefix = null;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
public int getValue(String key) throws NullPointerException {
String prefixedKey = applyPrefixOrDefault(key);
return inMemoryCache.get(prefixedKey);
}
public void setValue(String key, int value) {
String prefixedKey = applyPrefixOrDefault(key);
inMemoryCache.put(prefixedKey, value);
}
public boolean isCached(String key) {
String prefixedKey = applyPrefixOrDefault(key);
return inMemoryCache.containsKey(prefixedKey);
}
private String applyPrefixOrDefault(String key) {
if (prefix == null) {
return key;
} else {
return prefix + key;
}
}
public static void main (String[] arg) {
Cache cache = new Cache();
cache.setPrefix("global:");
cache.setValue("id", 4);
int value = cache.getValue("id");
System.out.println(value);
}
}
这段代码向我提出了两个问题:
如果我有很多方法访问内部哈希表,将缓存在一个类中的行为与前缀在另一个类中的行为分开是否正确?
什么是最干净的测试方法?如果不考虑前缀,测试 getValue、setValue 和 isCached 很简单。使用前缀我们需要测试两件事,缓存的正确内部行为,我们还需要测试所有方法在访问数据之前调用 applyPrefixOrDefault。
这是一个常见的用例,我确信必须有一些设计模式来组织它。有什么想法吗?
【问题讨论】:
标签: testing design-patterns architecture software-design