单元测试FileStreamResult

时间:2019-02-28 23:34:48

标签: c# unit-testing filestreamresult

我正在使用ASP.NET Core 2.1 Api控制器,该控制器返回一个FileStreamResult。我的业务层返回一个MemoryStream对象,该对象已倒带到起始位置。我正在尝试做的是编写一个单元测试,以检查预期的MemoryStream是否从方法中返回。但是,当我尝试这样做时,测试方法只是挂起。我分别使用Automapper,NSubstitute和Xunit进行映射,模拟和测试。

        //Action Method
        [Route("Excel")]
        [HttpPost]
        [ProducesResponseType(typeof(string), 200)]
        public ActionResult CreateExcelExport([FromBody]ExportRequestApiModel exportRequest)
        {
            try
            {
                var records = _mapper.Map<IEnumerable<ExportRecord>>(exportRequest.Records);
                var result = _excelFileManager.GenerateFile(records, "sheet 1", 1);

                return new FileStreamResult(result, 
                    new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
                {
                    FileDownloadName = "export.xlsx"
                };
            }
            catch (Exception ex)
            {

                if (!(ex is BusinessException))
                    _logger?.LogError(LoggingEvents.GeneralException, ex, ex.Message);

                return StatusCode(StatusCodes.Status500InternalServerError);

            }
        }
        //Action Method test.
        [Fact]
        public void CanCreateExportFile()
        {
            //Arrange
            var exportRequestApiModel = new ExportRequestApiModel()
            {
                Records = new List<ExportRecordApiModel>() { }
            };
            var exportRecords = new List<ExportRecord>
            {
                new ExportRecord()
            };
            _mapper.Map<IEnumerable<ExportRecord>>(exportRequestApiModel.Records)
                .Returns(exportRecords);

            _excelFileManager.GenerateFile(exportRecords, "sheet 1", 1)
                .Returns(new MemoryStream(){Position = 0});
            //Act
            var result = (ObjectResult) _controller.CreateExcelExport(exportRequestApiModel);
            //Assert
            Assert.Equal(StatusCodes.Status200OK, result.StatusCode);
            Assert.IsType<FileStream>(result.Value);
        }

0 个答案:

没有答案
相关问题