Use NUnit Assert.Throws method or ExpectedException attribute?

后端 未结 5 1256
温柔的废话
温柔的废话 2020-12-04 13:57

I have discovered that these seem to be the two main ways of testing for exceptions:

Assert.Throws(()=>MethodThatThrows());

[ExpectedExc         


        
5条回答
  •  攒了一身酷
    2020-12-04 14:20

    I prefer assert.throws since it allows me to verify and assert other conditions after the exception is thrown.

        [Test]
        [Category("Slow")]
        public void IsValidLogFileName_nullFileName_ThrowsExcpetion()
        {
            var a = new MyTestObject();
    
            // the exception we expect thrown from the IsValidFileName method
            var ex = Assert.Throws(() => a.IsValidLogFileName(""));
    
            // now we can test the exception itself
            Assert.That(ex.Message == "Blah");
    
        }
    

提交回复
热议问题