【问题标题】:UnitTest ExpectedException with multiple Exceptions具有多个异常的 UnitTest ExpectedException
【发布时间】: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


    【解决方案1】:

    问这个问题已经 7 年了,所以 Assert.ThrowsException 在 Microsoft.VisualStudio.TestTools.UnitTesting for Visual Studio 2017 中可用。

    Assert.ThrowsException<exception type goes here>(() =>
    {
        code that throw exception here
    });
    

    Assert.ThrowsException 在 Visual Studio 2015 中看起来并不存在。练习留给读者进行验证。

    【讨论】:

    • 是的,你是对的。我多年前的需求得到了满足...... :-)。但从我今天的观点来看,我不确定这是否是正确的测试...... :-)
    【解决方案2】:

    据我所知,使用属性是不可能的,因为当你抛出异常时,方法的执行会被中断。因此,如果您在第一行有异常,则不会执行第二行。

    如果你真的需要这个功能,请使用 nUnit,它有:

    Assert.Throws<Exception>(delegate { /*Your code*/ });
    

    【讨论】:

    • or-type 多个异常怎么样?一次只会发生一个异常。这可以通过 mstest 实现吗?
    猜你喜欢
    • 1970-01-01
    • 2015-10-03
    • 2020-06-08
    • 1970-01-01
    • 2018-03-31
    • 1970-01-01
    • 2013-07-17
    • 1970-01-01
    • 2018-10-07
    相关资源
    最近更新 更多