我有一个将数据导出到 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
}
除了 FileDownloadName
和 ContentType
之外,我还想检查 result
的内容。
看来我应该查看 result.FileContents
,但它是一个 byte[]
。
如何获取文本字符串形式的结果
?
每次运行测试时,我的结果是否以 CSV 文件的形式保存在解决方案的某处?
最佳答案
在您的 Index 方法中,您使用以下代码将文本内容编码为字节:
return File(new UTF8Encoding().GetBytes(sb.ToString()), "text/csv", fileName);
要从字节到原始文本,您可以使用:
string textContents = new UTF8Encoding().GetString(result.FileContents);
结果不会以 CSV 格式保存在任何地方。
关于c# - 如何对 FileContentResult 进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37416756/