I have method which fetches list of files from FTP server, just like below:
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();
}
}
}
I'm trying to write UT, which would access my local directory instead of FTP.
Here is my 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();
I receive System.Net.WebException: "Access to the path 'D:\\SomePathToUnitTestsExecutionFolder\\XmlFiles' is denied."
Q: Is it possible to pass windows/network credentials to be used by WebRequest to access local folder instead of remote FTP in unit test?
[EDIT]
Note that I'm able to test fetching file contents, when providing local file path, instead of ftp one:
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);
}
Also I'm aware that what I do doesn't 100% feet definition of Unit Test, but I still think this is a good test.