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

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

    Since I'm disturbed by the verbosity of some of the new NUnit patterns, I use something like this to create code that is cleaner for me personally:

    public void AssertBusinessRuleException(TestDelegate code, string expectedMessage)
    {
        var ex = Assert.Throws(code);
        Assert.AreEqual(ex.Message, expectedMessage);
    }
    
    public void AssertException(TestDelegate code, string expectedMessage) where T:Exception
    {
        var ex = Assert.Throws(code);
        Assert.AreEqual(ex.Message, expectedMessage);
    }
    

    The usage is then:

    AssertBusinessRuleException(() => user.MakeUserActive(), "Actual exception message");
    

提交回复
热议问题