【问题标题】:How to unit test FileContentResult?如何对 FileContentResult 进行单元测试?
【发布时间】:2016-09-21 20:31:03
【问题描述】:

我有一个将数据导出到 CSV 文件的方法。

public FileContentResult Index(SearchModel search)
{    
    ...
    if (search.Action == SearchActionEnum.ExportToTSV)
    {
        const string fileName = "Result.txt";
        const string tab = "\t";
        var sb = BuildTextFile(result, tab);
        return File(new UTF8Encoding().GetBytes(sb.ToString()), "text/tsv", fileName);
    }
    if (search.Action == SearchActionEnum.ExportToCSV)
    {
        const string fileName = "Result.csv";
        const string comma = ",";
        var sb = BuildTextFile(result, comma);
        return File(new UTF8Encoding().GetBytes(sb.ToString()), "text/csv", fileName);
    }
    return null;
}

我的测试,在 NUnit 中:

[Test]
public void Export_To_CSV()
{
    #region Arrange
    ...
    #endregion

    #region Act

    var result = controller.Index(search);

    #endregion

    #region Assert
    result.ShouldSatisfyAllConditions(
        ()=>result.FileDownloadName.ShouldBe("Result.csv"),
        ()=>result.ContentType.ShouldBe("text/csv")
        );
    #endregion
}

除了FileDownloadNameContentType之外,我想查看result的内容。

看来我应该看看result.FileContents,但它是byte[]

如何获取result 作为文本字符串?

每次我运行测试时,我的结果是否以 CSV 文件的形式保存在解决方案中的某个位置?

【问题讨论】:

    标签: c# asp.net-mvc unit-testing nunit


    【解决方案1】:

    在您的 Index 方法中,您使用以下代码将文本内容编码为字节:

    return File(new UTF8Encoding().GetBytes(sb.ToString()), "text/csv", fileName);
    

    要从字节中获取原始文本,您可以使用:

    string textContents = new UTF8Encoding().GetString(result.FileContents);
    

    结果不会以 CSV 格式保存在任何地方。

    【讨论】:

      【解决方案2】:

      在您进行测试时,您的 CSV 文件不会自动保存。当您收到响应时,它是原始响应。由您来保存。

      要将二进制字节数组转换为字符串,可以使用

      string csv = System.Text.Encoding.UTF8.GetString(result.FileContents);
      

      这不是我的想法,所以可能需要修复。

      【讨论】:

        猜你喜欢
        • 2012-01-08
        • 1970-01-01
        • 2019-11-02
        • 1970-01-01
        • 1970-01-01
        • 2013-09-30
        • 2019-01-05
        • 2011-03-16
        • 2013-01-02
        相关资源
        最近更新 更多