1

我正在开发一个 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);
        }
4

0 回答 0