我有从 FTP 服务器获取文件列表的方法,如下所示:
public List<string> FetchFilesList()
{
var request = WebRequest.Create(FtpServerUri);
request.Method = WebRequestMethods.Ftp.ListDirectory;
request.Credentials = Credentials;
using (var response = request.GetResponse())
{
var responseStream = response.GetResponseStream();
using (var reader = new StreamReader(responseStream))
{
var fileNamesString = reader.ReadToEnd();
var fileNames = fileNamesString.Split(
Environment.NewLine.ToCharArray(),
StringSplitOptions.RemoveEmptyEntries);
return fileNames.ToList();
}
}
}
我正在尝试编写 UT,它将访问我的本地目录而不是 FTP。
这是我的UT:
// ftpFetcherTestWrapper is thin wrapper to expose properties to UT
// TODO: For some reason providing credentials like this doesn't work :(
// It also doesn't work for DefaultNetworkCredentials
ftpFetcherTestWrapper.CredentialsExposed = CredentialCache.DefaultCredentials;
// As we are using wrapper we substitude FtpServerUri to our fake-local folder
ftpFetcherTestWrapper.ServerUriExposed = new Uri(directoryName);
var filesList = ftpSFetcherTestWrapper.FetchFilesList();
我收到System.Net.WebException: "Access to the path 'D:\\SomePathToUnitTestsExecutionFolder\\XmlFiles' is denied."
问:是否可以通过 WebRequest 使用的 Windows/网络凭据来访问本地文件夹而不是单元测试中的远程 FTP?
[编辑]
请注意,在提供本地文件路径而不是 ftp 时,我可以测试获取文件内容:
public XDocument FetchFile(string fileName)
{
var client = new WebClient();
client.Credentials = Credentials;
var fileUri = new Uri(FtpServerUri, fileName);
var downloadedXml = client.DownloadString(fileUri);
return XDocument.Parse(downloadedXml);
}
我也知道我所做的并不是 100% 定义单元测试,但我仍然认为这是一个很好的测试。