如何从包含ExcelFile作为字符串的http响应转换回实例ExcelFile(library GemBox)? C#

时间:2019-03-25 10:12:34

标签: c# excel httprequest integration-testing

我想为我的控制器编写集成测试,该测试返回带有“ Content”作为字符串及其内容的HttpResponseMessage。 内容类型为“ application / vnd.openxmlformats-officedocument.spreadsheetml.sheet”

我如何将此字符串转换回实例ExcelFile-libarary gembox?

例如该控制器:

        /// <summary>
        /// Save Data
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        [Route(Routes.Download)]
        [ValidateToken]
        [SwaggerResponse(HttpStatusCode.OK, "Xlsx-file with result", typeof(HttpStatusCode))]
        [SwaggerResponse(HttpStatusCode.Unauthorized, "invalid token", typeof(HttpStatusCode))]
        [SwaggerResponse(HttpStatusCode.BadRequest, "Message with description error of validate", typeof(HttpStatusCode))]
        public HttpResponseMessage PostUnloadExcelFile([FromBody]DownloadRequest request)
        {
            var logData = _logMessageBuilder.GetLogMessageDownload(request.Request);

            LogRequest(logData);

            var response = Request.CreateResponse(HttpStatusCode.OK);

            _downloadService.GetExcelFile(request.Data).Save(response, $"{Routes.Download}.xlsx");

            return response;
        }

此示例DownloadService

public class DownloadService : BaseDownloadService, IDownloadService
    {
        private const string Sheet = "Work sheet";      
        public ExcelFile GetExcelFile(IList<Event> data)
        {
            var xlsFile = new ExcelFile();
            var workSheet = xlsFile.Worksheets.Add(Sheet);

            SetHeaderWorksSheet(workSheet);

            for (var i = 0; i < data.Count; i++)
            {
                SetCellWorksSheet(data[i], workSheet, i);
            }

            for (var j = 0; j < data.Count + 1; j++)
            {
                SetCellStyleWorksSheet(workSheet, j);
            }
            return xlsFile;
        }
    }

    public class BaseDownloadService
    {

        protected void SetHeaderWorksSheet(ExcelWorksheet workSheet)
        {
            workSheet.Cells[0, ExcelFileIndexes.Item].Value = ConstantsExcelHeader.Item;
            workSheet.Cells[0, ExcelFileIndexes.FirstDate].Value = ConstantsExcelHeader.FirstDate;
            workSheet.Cells[0, ExcelFileIndexes.LastDate].Value = ConstantsExcelHeader.LastDate;

        }

        protected void SetCellWorksSheet(Triplet rowData, ExcelWorksheet workSheet, int i)
        {
            workSheet.Cells[i + 1, ExcelFileIndexes.Item].Value = (i + 1).ToString();
            workSheet.Cells[0, ExcelFileIndexes.FirstDate].Value = rowData.FirstDate;
            workSheet.Cells[0, ExcelFileIndexes.LastDate].Value = rowData.LastDate;

        }

        protected void SetCellStyleWorksSheet(ExcelWorksheet workSheet, int i)
        {
            workSheet.Columns[i].AutoFit();
            workSheet.Cells[0, i].Style
                .FillPattern
                .SetPattern(
                    FillPatternStyle.Solid,
                    SpreadsheetColor.FromName(ColorName.LightGreen),
                    SpreadsheetColor.FromName(ColorName.LightGreen));
        }
    }

例如此测试

        [Theory]
        [MemberData(nameof(DataForTrySaveInExcelFileTesting))]
        public async Task Should_ReturnCode200TrySaveDataInFileExcel(DownloadRequest request)
        {
            // Arrange
            var token = await GetValidTokenAsync();
            // Act
            var response = await ActAsync<DownloadRequest, DataRecord>(request, token, DownloadUrl);

            var excelBytes = Encoding.UTF8.GetBytes(response.Content);
            var excelFile = new ExcelFile();      

            using (MemoryStream stream = new MemoryStream())
            {
                stream.Write(excelBytes, 0, excelBytes.Length);
                stream.Position = 0;
                excelFile = ExcelFile.Load(stream, LoadOptions.XlsxDefault);
            }

            var ws = excelFile.Worksheets.ActiveWorksheet;
            ws.Cells["B2"].Value.ShouldBeEqualTo("1234567890");
        }


这是对前面的回应

this respone for front

1 个答案:

答案 0 :(得分:0)

jdweng谢谢您,您让我开始思考并提出了一个好主意。我们拒绝在流中转换字符串,我们只是扩展了requset帖子的响应模型,并为内容添加了流,如下所示。

const client = mqtt.connect("...")
const clientOnObs = bindCallback(client.on).bind(client)
clientOnObs('connect').subscribe(console.log)
    protected async Task<TestRequestResponse> PostAsync<TPayload>(string url, TPayload payload, string token = null)
        {
            using (var server = new HttpServer(_config))
            {
                var client = new HttpClient(server);

                var request = new HttpRequestMessage
                {
                    RequestUri = new Uri(url),
                    Method = HttpMethod.Post,
                    Content = new ObjectContent<TPayload>(payload, new JsonMediaTypeFormatter())
                };

                request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                request.Headers.Add("token", token);

                var httpRequest = new HttpRequest(string.Empty, url, string.Empty);
                httpRequest.AddServerVariable("UserHostAddress", "192.168.1.1");
                httpRequest.AddServerVariable("UserAgent", "chrome");
                HttpContext.Current = new HttpContext(httpRequest, new HttpResponse(new StringWriter()));

                using (var response = await client.SendAsync(request))
                {
                    var streamContent = await response.Content.ReadAsStreamAsync();
                    var memoryStream = new MemoryStream();
                    streamContent.CopyTo(memoryStream);
                    memoryStream.Position = 0;
                    var content = await response.Content.ReadAsStringAsync();

                    return new TestRequestResponse
                    {
                        Content = content,
                        StatusCode = response.StatusCode,
                        Message = response.ReasonPhrase,
                        StreamContent = memoryStream
                    };
                }
            }
        }