英文:
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");
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论