是否可以为此代码编写合理的单元测试,通过将其委托给主机系统上的有用工具(如果存在)来提取rar存档?我可以根据我的机器运行linux并安装unrar工具来编写一个测试用例,但是如果另一个运行windows的开发人员检查代码,测试会失败,尽管提取器代码没有任何问题.我需要找到一种方法来编写一个没有绑定到系统和unrar工具的有意义的测试.你会如何解决这个问题?
public class Extractor {
private EventBus eventBus;
private ExtractCommand[] linuxExtractCommands = new ExtractCommand[]{new LinuxUnrarCommand()};
private ExtractCommand[] windowsExtractCommands = new ExtractCommand[]{};
private ExtractCommand[] macExtractCommands = new ExtractCommand[]{};
@Inject
public Extractor(EventBus eventBus) {
this.eventBus = eventBus;
}
public boolean extract(DownloadCandidate downloadCandidate) {
for (ExtractCommand command : getSystemSpecificExtractCommands()) {
if (command.extract(downloadCandidate)) {
eventBus.fireEvent(this, new ExtractCompletedEvent());
return true;
}
}
eventBus.fireEvent(this, new ExtractFailedEvent());
return false;
}
private ExtractCommand[] getSystemSpecificExtractCommands() {
String os = System.getProperty("os.name");
if (Pattern.compile("linux", Pattern.CASE_INSENSITIVE).matcher(os).find()) {
return linuxExtractCommands;
} else if (Pattern.compile("windows", Pattern.CASE_INSENSITIVE).matcher(os).find()) {
return windowsExtractCommands;
} else if (Pattern.compile("mac os x", Pattern.CASE_INSENSITIVE).matcher(os).find()) {
return macExtractCommands;
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
}
您是否可以将类传递给Map<String,ExtractCommand[]>实例,然后创建一个抽象方法,例如GetOsName,使字符串匹配.然后你可以在地图中查找匹配字符串以获取getSystemSpecificExtractCommands方法中的提取命令.这将允许您注入包含模拟的列表ExtractCommand并覆盖该GetOsName方法以返回模拟命令的键,因此您可以测试当提取工作时,eventBus触发等.
private Map<String,EvenetCommand[]> eventMap;
@Inject
public Extractor(EventBus eventBus, Map<String,EventCommand[]> eventMap) {
this.eventBus = eventBus;
this.eventMap = eventMap;
}
private ExtractCommand[] getSystemSpecificExtractCommands() {
String os = GetOsName();
return eventMap.Get(os);
}
protected GetOsName();
{
return System.getProperty("os.name");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
266 次 |
| 最近记录: |