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); }
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); }
You can use a MemoryStream to provide a purely in-memory stream for your test.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With