Could someone guide me how to write a test for a method that returns Ienumerable ?
Here\'s my method -
public IEnumerable fetchFiles()
{
To make the code more testable inject IOWrapper
as a dependency. You can make it mockable by declaring an interface on IOWrapper
or by making the methods virtual. During your test you can then inject the mock instead of the concrete instance and make your test a true unit test.
public class CSVFileFinder
{
private readonly IOWrapper ioWrapper;
private readonly string folderPath;
public CSVFileFinder(string folderPath)
: this(new IOWrapper(), folderPath)
{
}
public CSVFileFinder(IOWrapper ioWrapper, string folderPath)
{
this.ioWrapper = ioWrapper;
this.folderPath = folderPath;
}
public IEnumerable<string> FetchFiles()
{
return this.ioWrapper.GetFiles(folderPath, "*.csv", SearchOption.AllDirectories);
}
}
Here's an example unit tests that verifies the result of IOWrapper
is returned from GetFiles
. This is written using Moq
and NUnit
.
[TestFixture]
public class FileFinderTests
{
[Test]
public void Given_csv_files_in_directory_when_fetchFiles_called_then_return_file_paths_success()
{
// arrange
var inputPath = "inputPath";
var testFilePaths = new[] { "path1", "path2" };
var mock = new Mock<IOWrapper>();
mock.Setup(x => x.GetFiles(inputPath, It.IsAny<string>(), It.IsAny<SearchOption>()))
.Returns(testFilePaths).Verifiable();
var testClass = new CSVFileFinder(mock.Object, inputPath);
// act
var result = testClass.FetchFiles();
// assert
Assert.That(result, Is.EqualTo(testFilePaths));
mock.VerifyAll();
}
}
You could then add tests for edge conditions like exception getting thrown by IOWrapper or no files returned etc. IOWrapper
is tested in isolation with it's own set of tests.
You need some testing framework. You can use MS Test embedded in Visual Studio - add a new Test project to your solution. Or you can use, for instance, NUnit which I am using.
[TestFixture] // NUnit attribute for a test class
public class MyTests
{
[Test] // NUnit attribute for a test method
public void fetchFilesTest() // name of a method you are testing + Test is a convention
{
var files = fetchFiles();
Assert.NotNull(files); // should pass if there are any files in a directory
Assert. ... // assert any other thing you are sure about, like if there is a particular file, or specific number of files, and so forth
}
}
For a complete list of possible asserts in NUnit navigate here. Also thanks to user xxMUROxx for pointing out the CollectionAssert class.
Additionaly, for test methods with many lines you would probably want it to be readable, so search for "Arrange Act Assert (AAA) Pattern" on the internet.
One more thing, there is already one question about testing IEnumerables here on SO.