代码之家  ›  专栏  ›  技术社区  ›  Rehan Shah

导致UnitTest中断的ThrowingException?

  •  2
  • Rehan Shah  · 技术社区  · 6 年前

    我遇到了这样的情况:在某些情况下,实际函数抛出了一个异常,我为它编写了单元测试,但不幸的是,单元测试失败了。

    样例代码 :

    // 'CheckNumber()' function is Present in 'Number' class.
    
    public int CheckNumber(int Number)
    {
        if (Number < 0 || Number > MaxNumber) // MaxNumber = 300
           throw new ArgumentOutOfRangeException();
    
        //..     
    }     
    

    单元测试 :

    我正在使用 NUnt框架 .

    // When The Number is Less than Zero Or Greater than Maximun Number
    
    [Test]
    public void CheckNumberTest()
    {
       Number number = new Number();
       int returnedValue = number.CheckNumber(-1);
    
       // Assertion.
       Assert.That(returnedValue , Throws.ArgumentOutOfRangeException);
    }
    

    运行测试时,此测试失败。这个测试实际上正在抛出异常,testmethod将要中断吗?那么如何修复呢?

    2 回复  |  直到 6 年前
        1
  •  1
  •   Johnny    6 年前

    这里的问题是,您的方法不返回任何值,而是抛出异常。

    int returnedValue = number.CheckNumber(-1); //throws ArgumentOutOfRangeException
    

    测试代码像其他代码一样执行,在有人捕获异常之前,它将冒泡异常。在您的案例中,它被测试执行器捕获,因为您在这里没有任何try/catch块。

    编写测试的正确方法是使用 Assert.Throws<TException> .

    [Test]
    public void CheckNumberTest()
    {
        //Arrange
       Number number = new Number();
    
       //Act
       var throws = new TestDelegate(() => number.CheckNumber(-1));
    
       //Assert.
       Assert.Throws<ArgumentOutOfRangeException>(throws);
    }
    
        2
  •  1
  •   M.Elfeky    6 年前

    请检查文档 here !

    当然,您需要理解同一链接中异常之间的差异。 这应该有助于你彻底

    // Require an ApplicationException - derived types fail!
    Assert.Throws( typeof(ApplicationException), code );
    Assert.Throws<ApplicationException>()( code );
    
    // Allow both ApplicationException and any derived type
    Assert.Throws( Is.InstanceOf( typeof(ApplicationException), code );
    Assert.Throws( Is.InstanceOf<ApplicationException>(), code );
    
    // Allow both ApplicationException and any derived type
    Assert.Catch<ApplicationException>( code );
    
    // Allow any kind of exception
    Assert.Catch( code )