如何对 FileContentResult 进行单元测试?

Bla*_*ise 3 c# asp.net-mvc nunit unit-testing

我有一个将数据导出到 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;
}
Run Code Online (Sandbox Code Playgroud)

我在 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
}
Run Code Online (Sandbox Code Playgroud)

除了FileDownloadName和之外ContentType,我还想检查 的内容result

看来我应该研究一下result.FileContents,但它是一个byte[]

我怎样才能得到result作为文本字符串?

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

Ric*_*ard 6

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

return File(new UTF8Encoding().GetBytes(sb.ToString()), "text/csv", fileName);
Run Code Online (Sandbox Code Playgroud)

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

string textContents = new UTF8Encoding().GetString(result.FileContents);
Run Code Online (Sandbox Code Playgroud)

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