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

前端 未结 9 1772
悲哀的现实
悲哀的现实 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:48

    With most .net unit testing frameworks you can put an [ExpectedException] attribute on the test method. However this can't tell you that the exception happened at the point you expected it to. That's where xunit.net can help.

    With xunit you have Assert.Throws, so you can do things like this:

        [Fact]
        public void CantDecrementBasketLineQuantityBelowZero()
        {
            var o = new Basket();
            var p = new Product {Id = 1, NetPrice = 23.45m};
            o.AddProduct(p, 1);
            Assert.Throws(() => o.SetProductQuantity(p, -3));
        }
    

    [Fact] is the xunit equivalent of [TestMethod]

提交回复
热议问题