C# 具有多个异常的UnitTest ExpectedException
我想要一个TestMethod来处理多个异常。问题是Testmethod在第一次抛出异常后停止 我知道我可以做这样的事情:C# 具有多个异常的UnitTest ExpectedException,c#,unit-testing,exception,C#,Unit Testing,Exception,我想要一个TestMethod来处理多个异常。问题是Testmethod在第一次抛出异常后停止 我知道我可以做这样的事情: try { sAbc.ToInteger(); Assert.Fail(); // If it gets to this line, no exception was thrown } catch (ArgumentException) { } [TestMethod, ExpectedException(typeof(ArgumentException),
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();
}
[TestMethod, ExpectedException(typeof(ArgumentException), "...")]
public void StringToIntException()
{
sDecimal.ToInteger();
}
但我想使用以下代码库:
[TestMethod, ExpectedException(typeof(ArgumentException), "...")]
public void StringToIntException()
{
sAbc.ToInteger(); // throws an exception and stops here
sDecimal.ToInteger(); // throws theoretically a exception too...
}
我不想为每个可能的异常创建一个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();
}
[TestMethod, ExpectedException(typeof(ArgumentException), "...")]
public void StringToIntException()
{
sDecimal.ToInteger();
}
从2018-11-09开始编辑:
今天,这将根据扬·大卫·纳基维茨的建议起作用。但正如我已经提到的。从我今天的观点来看,这将是一个糟糕的测试设计。例如:
[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 = "," });
});
}
[TestMethod]
公共无效例外测试()
{
Assert.ThrowsException(()=>
{
int.Parse(“abc”);
});
AreEqual(0.1m,decimal.Parse(“0.1”,CultureInfo.InvariantCulture));
Assert.ThrowsException(()=>
{
Parse(“0.1”,新的NumberFormatInfo{NumberDecimalSeparator=“,”});
});
}
据我所知,使用属性是不可能的,因为当抛出异常时,方法的执行会中断。因此,如果第一行有异常,第二行将不会执行
如果您确实需要该功能,请使用nUnit,它具有:
Assert.Throws<Exception>(delegate { /*Your code*/ });
Assert.Throws(委托{/*您的代码*/});
问题提出至今已有7年,因此Microsoft.VisualStudio.TestTools.UnitTesting for Visual Studio 2017中提供了Assert.ThrowsException
Assert.ThrowsException<exception type goes here>(() =>
{
code that throw exception here
});
Assert.ThrowsException(()=>
{
在这里引发异常的代码
});
Assert.ThrowsException在Visual Studio 2015中似乎不存在。练习留给读者验证 如何处理或键入多个异常?一次只会发生一个异常。mstest可以实现吗?是的,你是对的。我多年前的需求得到了满足…:-)。但从我今天的观点来看,我不确定这是否是正确的测试…:-)