mas*_*_99 7 c# unit-testing exception
我想要一个TestMethod用于多个异常.问题是Testmethod在第一次抛出异常后停止.
我知道我可以这样做:
try
{
sAbc.ToInteger();
Assert.Fail(); // If it gets to this line, no exception was thrown
}
catch (ArgumentException) { }
Run Code Online (Sandbox Code Playgroud)
但我想使用以下代码库:
[TestMethod, ExpectedException(typeof(ArgumentException), "...")]
public void StringToIntException()
{
sAbc.ToInteger(); // throws an exception and stops here
sDecimal.ToInteger(); // throws theoretically a exception too...
}
Run Code Online (Sandbox Code Playgroud)
而且我不想为每个可能的异常创建一个testmethod:
[TestMethod, ExpectedException(typeof(ArgumentException), "...")]
public void StringToIntException()
{
sAbc.ToInteger();
}
[TestMethod, ExpectedException(typeof(ArgumentException), "...")]
public void StringToIntException()
{
sDecimal.ToInteger();
}
Run Code Online (Sandbox Code Playgroud)
编辑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 = "," });
});
}
Run Code Online (Sandbox Code Playgroud)
自提出问题以来已经过去了 7 年,因此 Assert.ThrowsException 可在 Microsoft.VisualStudio.TestTools.UnitTesting for Visual Studio 2017 中使用。
Assert.ThrowsException<exception type goes here>(() =>
{
code that throw exception here
});
Run Code Online (Sandbox Code Playgroud)
Assert.ThrowsException 看起来并不存在于 Visual Studio 2015 中。练习留给读者验证。
| 归档时间: |
|
| 查看次数: |
4290 次 |
| 最近记录: |