我正在测试解析CSV的C#应用程序的单元测试。我在94%的代码覆盖率,因为我不能强迫它失败try/catch块......我使用CsvHelper从的NuGet http://joshclose.github.io/CsvHelper失败try/catch块读取csv
public void ParseCsv([FromBody] string csvText)
{
var parseCsv = new XsvData(new[] { "\t", "," });
try
{
using (var reader = new XsvReader(new StringReader(csvText)))
{
parseCsv.Read(reader, headerExists: true);
}
}
catch (Exception)
{
var response = new HttpResponseMessage(HttpStatusCode.BadRequest)
{
Content = new StringContent("Unable to read CSV."),
ReasonPhrase = "Invalid CSV"
};
throw new HttpResponseException(response);
}
}
我试过路过的最不起眼的琴弦我能想到的它,但它使通过这个,后来就在函数出错了..
[TestMethod]
//[ExpectedException(typeof(HttpResponseException))]
public void TestUploadCsv_UploadingCsvNonCsv()
{
const string csvText = "[email protected] [email protected] fjkqeqir%[email protected] ujewqh$phfuw \n hfwu- ihfq&if*[email protected] afuhwu- [email protected]";
var context = GetMyFakeEntityDatabase();
var controller = new MyController(context);
controller.ParseCsv(csvText);
}
的try/catch块后,我有一个强制的所有头存在的部分,它在那里失败了,但是在这个例子中,它在阅读过程中应该失败。我如何强制我的单元测试失败?任何帮助表示赞赏!提前致谢。
+1用于测试代码如何处理失败。 – 2014-10-01 15:59:55
您可以将'null'传递给'csvText'。 – juharr 2014-10-01 16:01:14
@juharr它目前的写法,可以工作,但它不是一个非常通用的解决方案。如果他想要空/空字符串与无效语法的不同状态代码会怎样。 – 2014-10-01 16:08:45