如何对 FileContentResult 进行单元测试?
How to unit test FileContentResult?
我有一种方法可以将数据导出到 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[]
。
如何获取 result
作为文本字符串?
每次我 运行 测试时,我的结果是否作为 CSV 文件保存在解决方案的某处?
您的 CSV 文件不会在您进行测试时自动保存。当您得到响应时,它是原始响应。是否保存由您决定。
要将二进制字节数组转换为字符串,您可以使用
string csv = System.Text.Encoding.UTF8.GetString(result.FileContents);
这超出了我的头脑,因此可能需要修复。
在您的 Index 方法中,您使用以下代码将文本内容编码为字节:
return File(new UTF8Encoding().GetBytes(sb.ToString()), "text/csv", fileName);
从字节到原文,可以使用:
string textContents = new UTF8Encoding().GetString(result.FileContents);
结果不会以 CSV 格式保存在任何地方。
我有一种方法可以将数据导出到 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[]
。
如何获取 result
作为文本字符串?
每次我 运行 测试时,我的结果是否作为 CSV 文件保存在解决方案的某处?
您的 CSV 文件不会在您进行测试时自动保存。当您得到响应时,它是原始响应。是否保存由您决定。
要将二进制字节数组转换为字符串,您可以使用
string csv = System.Text.Encoding.UTF8.GetString(result.FileContents);
这超出了我的头脑,因此可能需要修复。
在您的 Index 方法中,您使用以下代码将文本内容编码为字节:
return File(new UTF8Encoding().GetBytes(sb.ToString()), "text/csv", fileName);
从字节到原文,可以使用:
string textContents = new UTF8Encoding().GetString(result.FileContents);
结果不会以 CSV 格式保存在任何地方。