2016-05-24 193 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); 

這就是把我的頭頂部,所以可能需要固定。

相關問題