Is a reasonable unit test possible?

Could there be a useful unit test for this code that extracts the rar archive, delegating it to a capable tool on the host system, if one exists? I can write a test case based on the fact that my machine starts linux and the unrar tool is installed, but if another developer who launches windows checks the code, the test will fail, although there is nothing wrong with the extractor code. I need to find a way to write a meaningful test that is not tied to the system and the unrar tool installed. How would you handle this?

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;
}

}

+3
source share
4 answers

a Map<String,ExtractCommand[]>, , GetOsName, . , extract getSystemSpecificExtractCommands. , mock ExtractCommand, GetOsName, mock, , 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");
}
+6
+1

. , , , .

, Extract, , , , Extract . , .

, , . , ExtractCommand .

, , .

.

. , , , .

+1

, , . - .

1 , , , Java , .

. , , , , .

java, ( ), unit test, , . , "". unit test , (, RAR , - .)

, , , . , . , , .

, , , LinuxUnrarer Windows. java , . , , .

Regarding the UNRAR cross platform, there is a java RAR scanner , but it does not decompress.

+1
source

Source: https://habr.com/ru/post/1743069/


All Articles