2016-05-24 191 views
0

我有一种将数据导出到CSV文件的方法。如何对FileContentResult进行单元测试?

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文件中?

回答

0

索引中的方法,则需要使用下面的代码到文本内容的字节编码为:

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

要从字节的原始文本得到,你可以使用:

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

结果不作为CSV保存在任何位置。

0

您的CSV文件将不会在您做测试时自动保存。当你得到回应时,这是最原始的回应。这将取决于你保存它。

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

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

这就是把我的头顶部,所以可能需要固定。

相关问题