检测符号链接文件的方法的单元测试

huangapple go评论61阅读模式
英文:

Unit test for a method that detects files that are symbolic links

问题

我需要在Java中编写一个单元测试,用于检测符号链接文件的方法。该测试将需要创建临时的符号链接文件。问题在于在Windows 10上,以及可能在其他版本的Windows上,单元测试需要管理员权限才能创建符号链接。有没有人知道如何在单元测试中处理类似这样的特殊情况?

英文:

I need to write a unit test in Java for a method that detects files that are symbolic links. The test would have to create temporary files that are symbolic links. The trouble is that on Windows 10, and probably other versions of Windows, the unit test would need admin privileges to create a symbolic link. Does anyone have a way to handle special-case issues like this in unit tests?

答案1

得分: 1

这是您提供的代码的翻译:

import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

public class SymbolicLinkDetectorTest {

    @Test
    public void testDetectSymbolicLink() throws IOException {
        File tempFile = createTempFile();
        if (isSymbolicLinkSupported()) {
            Files.createSymbolicLink(tempFile.toPath(), new File("c:\\temp").toPath());
            assert SymbolicLinkDetector.detectSymbolicLink(tempFile);
        } else {
            assert !SymbolicLinkDetector.detectSymbolicLink(tempFile);
        }
    }

    private File createTempFile() throws IOException {
        File tempFile = File.createTempFile("test", ".tmp");
        tempFile.deleteOnExit();
        return tempFile;
    }

    private boolean isSymbolicLinkSupported() {
        return System.getProperty("os.name").toLowerCase().contains("linux");
    }
}

请注意,我已经将双引号 " 替换为正常的双引号以获得有效的 Java 代码。

英文:
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

public class SymbolicLinkDetectorTest {

    @Test
    public void testDetectSymbolicLink() throws IOException {
        File tempFile = createTempFile();
        if (isSymbolicLinkSupported()) {
            Files.createSymbolicLink(tempFile.toPath(), new File("c:\\temp").toPath());
            assert SymbolicLinkDetector.detectSymbolicLink(tempFile);
        } else {
            assert !SymbolicLinkDetector.detectSymbolicLink(tempFile);
        }
    }

    private File createTempFile() throws IOException {
        File tempFile = File.createTempFile("test", ".tmp");
        tempFile.deleteOnExit();
        return tempFile;
    }

    private boolean isSymbolicLinkSupported() {
        return System.getProperty("os.name").toLowerCase().contains("linux");
    }
}

huangapple
  • 本文由 发表于 2023年4月17日 04:44:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76030249.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定