如何模拟ExcelReaderFactory.CreateReader并返回IExcelDataReader数据

时间:2019-07-19 11:39:38

标签: .net-core moq azure-storage-blobs xunit

我正在使用xUnit和Moq编写单元测试。

我的 ExcelData 类具有以下代码

       public DataTable ReadFromExcel(CloudBlockBlob MasterDataSourceBlob, string SheetName)
        {
            DataTable dataInExcelSheet = new DataTable();
            using (var memoryStream = new MemoryStream())
            {
                MasterDataSourceBlob.DownloadToStreamAsync(memoryStream);
                var headers = new List<string>();
               IExcelDataReader excelReader = ExcelReaderFactory.CreateReader(memoryStream);
          }

为了模拟ExcelReaderFactory.CreateReader(),我如下创建了新的类和接口,并返回了 IExcelDataReader

ExcelDataMock.cs 文件具有以下代码

   public  class ExcelDataMock
    {

        public IExcelDataReader CreateReader(MemoryStream memoryStream)
        {
           return ExcelReaderFactory.CreateReader(memoryStream); 
        }
    }

IExcelDataMock.cs 文件具有以下代码

   public interface IExcelDataMock
    {
        IExcelDataReader CreateReader(MemoryStream memoryStream);
    }

我的测试班级有下面的代码

      [Fact]
        public void ReadFromExcel_Success()
        {
            var stream = new MemoryStream();
            var writer = new StreamWriter(stream);
            writer.Write("sample data");
            writer.Flush();
            stream.Position = 0;

            var mockExcelDataMock = new Mock<IExcelDataMock>();
            mockExcelDataMock.Setup(data => data.CreateReader(It.IsAny<MemoryStream>())).Returns<IExcelDataReader>(
                excel =>
            {

                var item = new Mock<IExcelDataReader>();

                return item.Object;
            }
            );


            var mockCloudBlockBlob = new Mock<CloudBlockBlob>(new Uri("https://samplestorage.blob.core.windows.net/samplecontainer"));


            mockCloudBlockBlob.Setup(blob => blob.DownloadToStreamAsync(It.IsAny<Stream>()))
                .Callback((Stream target) => stream.CopyTo(target)) 
                .Returns(Task.CompletedTask);


            string SheetName = null;

            this._iExcelOperations = new ExcelData(mockExcelDataMock.Object);

            this._iExcelOperations.ReadFromExcel(mockCloudBlockBlob.Object, SheetName);

        }

enter image description here

如果我使用ExcelReaderFactory.CreateReader(memoryStream),则会遇到错误消息

  

没有数据可用于编码1252。有关定义   自定义编码,请参见文档   Encoding.RegisterProvider方法。'

如果我使用this._iExcelOperationsMock.CreateReader(memoryStream),则会收到如下错误消息

  

System.ArgumentException:'类型为'System.IO.MemoryStream'的对象'   不能转换为类型'ExcelDataReader.IExcelDataReader'。

enter image description here

如何解决此问题。

更新1:

错误:

  

无效的文件签名

enter image description here

0 个答案:

没有答案