【发布时间】:2011-11-23 07:55:19
【问题描述】:
我想要一个 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, ExpectedException(typeof(ArgumentException), "...")]
public void StringToIntException()
{
sAbc.ToInteger();
}
[TestMethod, ExpectedException(typeof(ArgumentException), "...")]
public void StringToIntException()
{
sDecimal.ToInteger();
}
2018 年 11 月 9 日编辑:
今天,这将根据 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 = "," });
});
}
【问题讨论】:
标签: c# unit-testing exception