How do I use Assert.Throws to assert the type of the exception?

后端 未结 7 1508
你的背包
你的背包 2020-12-02 04:51

How do I use Assert.Throws to assert the type of the exception and the actual message wording?

Something like this:

Assert.Throws

        
相关标签:
7条回答
  • 2020-12-02 05:50

    To expand on persistent's answer, and to provide more of the functionality of NUnit, you can do this:

    public bool AssertThrows<TException>(
        Action action,
        Func<TException, bool> exceptionCondition = null)
        where TException : Exception
    {
        try
        {
            action();
        }
        catch (TException ex)
        {
            if (exceptionCondition != null)
            {
                return exceptionCondition(ex);
            }
            return true;
        }
        catch
        {
            return false;
        }
    
        return false;
    }
    

    Examples:

    // No exception thrown - test fails.
    Assert.IsTrue(
        AssertThrows<InvalidOperationException>(
            () => {}));
    
    // Wrong exception thrown - test fails.
    Assert.IsTrue(
        AssertThrows<InvalidOperationException>(
            () => { throw new ApplicationException(); }));
    
    // Correct exception thrown - test passes.
    Assert.IsTrue(
        AssertThrows<InvalidOperationException>(
            () => { throw new InvalidOperationException(); }));
    
    // Correct exception thrown, but wrong message - test fails.
    Assert.IsTrue(
        AssertThrows<InvalidOperationException>(
            () => { throw new InvalidOperationException("ABCD"); },
            ex => ex.Message == "1234"));
    
    // Correct exception thrown, with correct message - test passes.
    Assert.IsTrue(
        AssertThrows<InvalidOperationException>(
            () => { throw new InvalidOperationException("1234"); },
            ex => ex.Message == "1234"));
    
    0 讨论(0)
提交回复
热议问题