Testing a function that returns IEnumerable

前端 未结 2 1782
余生分开走
余生分开走 2021-01-27 05:34

Could someone guide me how to write a test for a method that returns Ienumerable ?

Here\'s my method -

public  IEnumerable fetchFiles()
{          


        
2条回答
  •  礼貌的吻别
    2021-01-27 05:52

    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.

提交回复
热议问题