Search code examples
c#unit-testingstream

How to write unitTest for methods using a stream as a parameter


I have class ImportProvider , and I want write unit test for Import method.

But this should be unit test, so I don't want to read from file to stream. Any idea?

public class ImportProvider : IImportProvider
{ 
     public bool Import(Stream stream)
     {
         //Do import

         return isImported;
     }
}

public interface IImportProvider
{
      bool Import(Stream input);
}

This is unit test:

[TestMethod]
public void ImportProvider_Test()
{
    // Arrange           
    var importRepository = new Mock<IImportRepository>(); 
    var imp = new ImportProvider(importRepository.Object);
    //Do setup...

    // Act
    var test_Stream = ?????????????
    // This working but not option:
    //test_Stream = File.Open("C:/ExcelFile.xls", FileMode.Open, FileAccess.Read);
    var result = imp.Import(test_Stream);

    // Assert    
    Assert.IsTrue(result);
}

Solution

  • Use a MemoryStream. Not sure what your function expects, but to stuff a UTF-8 string into it for example:

    //Act
    using (var test_Stream = new MemoryStream(Encoding.UTF8.GetBytes("whatever")))
    {
        var result = imp.Import(test_Stream);
    
        // Assert    
        Assert.IsTrue(result);
    }
    

    EDIT: If you need an Excel file, and you are unable to read files from disk, could you add an Excel file as an embedded resource in your test project? See How to embed and access resources by using Visual C#

    You can then read as a stream like this:

    //Act
    using (var test_Stream = this.GetType().Assembly.GetManifestResourceStream("excelFileResource"))
    {
        var result = imp.Import(test_Stream);
    
        // Assert    
        Assert.IsTrue(result);
    }