C# 如何对FileContentResult进行单元测试?
我有一个将数据导出到CSV文件的方法C# 如何对FileContentResult进行单元测试?,c#,asp.net-mvc,unit-testing,nunit,C#,Asp.net Mvc,Unit Testing,Nunit,我有一个将数据导出到CSV文件的方法 public FileContentResult Index(SearchModel search) { ... if (search.Action == SearchActionEnum.ExportToTSV) { const string fileName = "Result.txt"; const string tab = "\t"; var sb = BuildText
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;
}
我在努伊特的测试:
[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
}
除了FileDownloadName
和ContentType
,我还想检查结果的内容
似乎我应该查看result.FileContents
,但它是一个字节[]
如何将结果作为文本字符串保存
每次运行测试时,我的结果是否作为CSV文件保存在解决方案中的某个位置?您的CSV文件不会在执行测试时自动保存。当您得到响应时,它是原始响应。这将由你来拯救它
要将二进制字节数组转换为字符串,可以使用
string csv = System.Text.Encoding.UTF8.GetString(result.FileContents);
这是我不知道的,因此可能需要修复。在索引方法中,您使用以下代码将文本内容编码为字节:
return File(new UTF8Encoding().GetBytes(sb.ToString()), "text/csv", fileName);
要将字节转换为原始文本,可以使用:
string textContents = new UTF8Encoding().GetString(result.FileContents);
结果不会作为CSV保存在任何位置