Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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); } 
like image 592
Raskolnikov Avatar asked May 13 '15 10:05

Raskolnikov


2 Answers

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); } 
like image 130
GazTheDestroyer Avatar answered Oct 05 '22 21:10

GazTheDestroyer


You can use a MemoryStream to provide a purely in-memory stream for your test.

like image 23
James Lucas Avatar answered Oct 05 '22 21:10

James Lucas