测试返回IEnumerable 的函数

有人可以指导我如何为返回Ienumerable的方法编写测试吗?

这是我的方法 –

public IEnumerable fetchFiles() { IOWrapper ioWrapper = new IOWrapper(); var files = ioWrapper.GetFiles(folderPath, "*.csv", SearchOption.AllDirectories); return files; } 

我刚开始学习unit testing。 如果有人解释我如何去做,我真的很感激。

你需要一些测试框架。 您可以使用Visual Studio中嵌入的MS Test – 将新的Test项目添加到您的解决方案中。 或者你可以使用我正在使用的NUnit。

 [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 } } 

有关NUnit中可能断言的完整列表,请在此处导航。 还要感谢用户xxMUROxx指出CollectionAssert类。

另外,对于有许多行的测试方法,您可能希望它是可读的,因此在互联网上搜索“Arrange Act Assert(AAA)Pattern”。

还有一件事,关于在SO上测试IEnumerables已经有一个问题了。

为了使代码更易于测试,请将IOWrapper注入依赖项。 您可以通过在IOWrapper上声明接口或将方法设置为虚拟来使其可模拟。 在测试期间,您可以注入模拟而不是具体实例,并使您的测试成为真正的unit testing。

 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); } } 

这是一个示例unit testing,用于validation从GetFiles返回IOWrapper的结果。 这是使用MoqNUnit编写的。

 [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(); } } 

然后,您可以添加边缘条件的测试,例如IOWrapper抛出的exception,或者不返回任何文件等IOWrapper使用它自己的一组测试进行IOWrapper测试。