Reputation: 531
I recently asked a question but but did not get an answer that I could act on. I think this was due to the long code sample included. I have decided to post another question with a much smaller code sample. I want to unit test the below method to make sure that it does work and to make sure that it deletes all .xml files in a specified directory.
private static void DeleteXmlFiles(string XmlFileDirectory)
{
foreach (var file in Directory.GetFiles(XmlFileDirectory, "*.Xml"))
{
File.Delete(file);
}
}
Does anybody have any unit testing code snippet that I can look at which would help me in this case?
The below is all i have in the Test method which basically is not much:
[Test]
public void can_delete_all_files_from_specified_directory()
{
string inputDir = @"C:\TestFiles\";
var sut = new FilesUtility();
var deleteSuccess = sut.
}
Upvotes: 2
Views: 2713
Reputation: 146409
one approach to such a test might be:
Upvotes: 1
Reputation: 236188
In order to unit-test your method, you should test it in isolation. I.e. there should not be any real classes like Directory
or File
your SUT interacts with. So, you have three options:
Last approach is pretty simple - create new folder before each test runs, and delete it after test run
private string path = @"C:\TestFiles\";
[SetUp]
public void Setup()
{
Directory.CreateDirectory(path);
}
[TearDown]
public void Deardown()
{
Directory.Delete(path);
}
[Test]
public void ShouldRemoveAllFilesFromSpecifiedDirectory()
{
// seed directory with sample files
FileUtility.DeleteXmlFiles(path);
Assert.False(Directory.EnumerateFiles(path).Any());
}
Upvotes: 3
Reputation: 11717
There's no way of testing methods like these with Moq or any other free mocking framework. That's because they cannot mock methods other than virtuals or interface implementations (which is roughly the same under the hood anyway).
To fake (not mock) system methods like File.Delete(...)
or static methods of any kind, you'll need something like Typemock (commercial) or MS Moles (not very user-friendly).
As a workaround, you could create a test directory along with some files in your test, call DeleteXmlFiles(...)
on it, and then check if the directory is empty. But that would be slow and also is not really a unit test but more like an integration test.
Upvotes: 1