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

后端 未结 7 1608
你的背包
你的背包 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:48

    I recently ran into the same thing, and suggest this function for MSTest:

    public bool AssertThrows(Action action) where T : Exception
    {
        try {action();
    }
    catch(Exception exception)
    {
        if (exception.GetType() == typeof(T))
            return true;
    }
        return false;
    }
    

    Usage:

    Assert.IsTrue(AssertThrows(delegate{ newMyMethod(MyParameter); }));
    

    There is more in Assert that a particular exception has occured (Assert.Throws in MSTest).

提交回复
热议问题