0

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

如何将此字符串转换回实例 ExcelFile - 库 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;
        }

这个例子下载服务

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");
        }


这是前面的回应

这个对前面的回应

4

1 回答 1

0

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

    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
                    };
                }
            }
        }
        [Theory]
        [MemberData(nameof(DataForTrySaveInExcelFileTesting))]
        public async Task Should_ReturnCode200TrySaveDataInFileExcel(DownloadRequest request)
        {
            // Arrange
            var token = await GetValidTokenAsync();

            // Act
            var responseBilling = await ActAsync<DownloadRequest, Record>(request, token, DownloadUrl);
            var excelFile = ExcelFile.Load(response.StreamContent, LoadOptions.XlsxDefault);

            var ws = excelFile.Worksheets.ActiveWorksheet;
            ws.Cells["E2"].Value.ShouldBeEqualTo("11111");
            ws.Cells["Q3"].Value.ShouldBeEqualTo("11111");
            ws.Cells["C4"].Value.ShouldBeEqualTo(11111);
            ws.Cells["F5"].Value.ShouldBeEqualTo("11111");
            ws.Cells["O6"].Value.ShouldBeEqualTo("11111");
            ws.Rows.Count.ShouldBeEqualTo(request.Data.Count + 1);
        }

        public async Task<TestRequsetResponse> ActAsync<TRequest, TItem>(TRequest reuqset = null, string token = null, string url = null) where TRequest : DownloadRequest<Item>
        {
            return await PostAsync(url, request, token);
        }

于 2019-03-26T09:37:04.227 回答