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 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();
mock.Setup(x => x.GetFiles(inputPath, It.IsAny(), It.IsAny()))
.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.