I'm working on a ASP.NET Core 2.1 Api controller that returns a FileStreamResult
. My business layer returns a MemoryStream
object that has been rewound to the start position. What I am trying to do is write a unit test that checks if the expected MemoryStream
is return from the method. However, when I attempt this, the test method just hangs. I'm using Automapper, NSubstitute and Xunit for mapping, mocking, and testing respectively.
//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);
}