Best way to test exceptions with Assert to ensure they will be thrown

前端 未结 9 1752
悲哀的现实
悲哀的现实 2020-12-02 06:58

Do you think that this is a good way for testing exceptions? Any suggestions?

Exception exception = null;
try{
    //I m sure that an exeption will happen he         


        
9条回答
  •  一生所求
    2020-12-02 07:47

    Suggest using NUnit's clean delegate syntax.

    Example for testing ArgumentNullExeption:

    [Test]
    [TestCase(null)]
    public void FooCalculation_InvalidInput_ShouldThrowArgumentNullExeption(string text)
    {
        var foo = new Foo();
        Assert.That(() => foo.Calculate(text), Throws.ArgumentNullExeption);
    
        //Or:
        Assert.That(() => foo.Calculate(text), Throws.Exception.TypeOf);
    }
    

提交回复
热议问题