Junit4测试的java运行时权限
我最近在为我正在开发的应用程序进行单元测试时遇到了一些麻烦。我正在测试的方法负责从远程FTP服务器复制文件并将其写入本地目录。最初,我有在单元测试本身中创建本地目录的代码。它起到了作用,但我意识到我让测试对我的应用程序代码中应该发生的事情负责。我将存在性检查和目录创建移到应用程序代码中,现在我的测试在尝试写入本地目录时抛出权限错误。问题似乎在于,我的应用程序代码是以不同于单元测试的用户身份执行的。由于目录是由以userA身份运行的应用程序创建的,因此以userB身份运行的单元测试不再具有向其中写入文件的权限
是否有某种方法可以指定我的测试应该以什么用户的身份运行,无论是在代码中还是在测试的eclipse设置中?有没有其他办法解决这个问题
一些代码示例:
@Test
public void testCopyEyeRepOrders() throws IOException, InterruptedException
{
File localDir = new File(newOrdersDir);
//if I do the directory creation here the test works but I'm duplicating work
//that should be done in the application
if( !localDir.exists())
{
localDir.mkdirs();
}
//call my service method to copy the files
ExportDataApi.copyEyeRepOrders(newOrdersDir, ftpDirectory);
File[] files = localDir.listFiles();
assertNotNull(files);
}
public static void copyEyeRepOrders(String localDirectory, String remoteDirectory) throws SocketException, IOException
{
File localDir = new File(localDirectory);
if( !localDir.exists())
{
localDir.mkdirs();
}
//get some files from the FTP server
...
if(files != null)
{
for(int i = 0; i < files.length; i++)
{
FTPFile f = files[i];
String filePath = remoteDirectory + "/" + f.getName();
//running the unit test will cause an error to be thrown here
//if the application created the target directory
FileOutputStream out = new FileOutputStream(localDirectory + "/" + f.getName());
ftpClient.retrieveFile(filePath, out);
out.close();
}
}
}
共 (0) 个答案