gpt4 book ai didi

java - 合理的单元测试可能吗?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:03:19 26 4
gpt4 key购买 nike

是否可以为这段代码编写一个合理的单元测试,通过将它委托(delegate)给主机系统上一个有能力的工具来提取 rar 存档(如果存在)?我可以根据我的机器运行 linux 并且安装了 unrar 工具的事实编写测试用例,但是如果另一个运行 windows 的开发人员检查代码,测试将失败,尽管提取器代码没有任何问题。我需要找到一种方法来编写一个没有绑定(bind)到系统和安装的 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;
}

最佳答案

你不能通过a类吗Map<String,ExtractCommand[]>实例,然后创建一个抽象方法,比如说 GetOsName , 用于获取要匹配的字符串。然后您可以在映射中查找匹配字符串以获取 getSystemSpecificExtractCommands 中的提取命令方法。这将允许您注入(inject)一个包含模拟 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");
}

关于java - 合理的单元测试可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2724945/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com