I have a method that exports data into CSV file.
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;
}
My test, in 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
}
In addition to FileDownloadName and ContentType, I want to check the content of the result.
It seems I should look into result.FileContents, but it is a byte[].
How can I get hold of the result as a text string?
And is my result saved somewhere as a CSV file in the solution every time I run the test?
In your Index method, you are using the following code to encode the text content as bytes:
return File(new UTF8Encoding().GetBytes(sb.ToString()), "text/csv", fileName);
To get from the bytes to the original text, you can use:
string textContents = new UTF8Encoding().GetString(result.FileContents);
The result is NOT saved anywhere as a CSV.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With