c# – 具有多个异常的UnitTest ExpectedException
发布时间:2020-12-15 07:50:02 所属栏目:百科 来源:网络整理
导读:我想要一个TestMethod用于多个异常.问题是Testmethod在第一次抛出异常后停止. 我知道我可以这样做: try { sAbc.ToInteger(); Assert.Fail(); // If it gets to this line,no exception was thrown} catch (ArgumentException) { } 但我想使用以下代码库: [
我想要一个TestMethod用于多个异常.问题是Testmethod在第一次抛出异常后停止.
我知道我可以这样做: try { sAbc.ToInteger(); Assert.Fail(); // If it gets to this line,no exception was thrown } catch (ArgumentException) { } 但我想使用以下代码库: [TestMethod,ExpectedException(typeof(ArgumentException),"...")] public void StringToIntException() { sAbc.ToInteger(); // throws an exception and stops here sDecimal.ToInteger(); // throws theoretically a exception too... } 而且我不想为每个可能的异常创建一个testmethod: [TestMethod,"...")] public void StringToIntException() { sAbc.ToInteger(); } [TestMethod,"...")] public void StringToIntException() { sDecimal.ToInteger(); } 编辑2018-11-09: 今天,这将基于Jan David Narkiewicz的建议.但正如我已经提到的那样.从我今天的观点来看,这对于测试来说是一个糟糕的设计.例: [TestMethod] public void ExceptionTest() { Assert.ThrowsException <FormatException> (() => { int.Parse("abc"); }); Assert.AreEqual(0.1m,decimal.Parse("0.1",CultureInfo.InvariantCulture)); Assert.ThrowsException<FormatException>(() => { decimal.Parse("0.1",new NumberFormatInfo { NumberDecimalSeparator = "," }); }); } 解决方法
问题问题已经过去了7年,所以Assert.ThrowsException可以在Visual Studio 2017的Microsoft.VisualStudio.TestTools.UnitTesting中找到.
Assert.ThrowsException<exception type goes here>(() => { code that throw exception here }); Assert.ThrowsException看起来不像Visual Studio 2015中存在.练习留给读者验证. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |