[NSub說明書] Page 7 - Throw Exception

NSubstitute -  Throw Exception
範例程式碼放在 GitHub

前言

當Exception產生時 也可以寫測試

產生Exception

直接看程式碼

    public class A06_Exception
    {
        public class Calculator
        {
            public virtual int Add(int a, int b)
            {
                return a + b;
            }

            public virtual void AddVoid(int a, int b, out int c)
            {
                c = a + b;
            }

        }

        [TestMethod]
        [ExpectedException(typeof(Exception))]
        public void NSubstituteNote14()
        {
            //arrange
            var calculator = Substitute.For<Calculator>();
            calculator.Add(1,2).Returns(x => { throw new Exception(); });

            //act
            //assert
            calculator.Add(1,2);
        }

        [TestMethod]
        [ExpectedException(typeof(Exception))]
        public void NSubstituteNote15()
        {
            //arrange
            var calculator = Substitute.For<Calculator>();
            var c = 0;
            calculator
                .When(x => x.AddVoid(1,2, out c))
                .Do(x => { throw new Exception(); });

            //act
            //assert
            calculator.AddVoid(1,2, out c);
        }

        [TestMethod]
        public void NSubstituteNote16()
        {
            //ref http://kevintsengtw.blogspot.tw/2015/09/nsubstitute-exception.html
            //arrange
            var calculator = Substitute.For<Calculator>();
            calculator.Add(1, 2).Returns(x => { throw new Exception("FluentAssertions"); });

            //act
            Action act = () => calculator.Add(1, 2);

            //assert
            act.ShouldThrow<Exception>()
               .WithMessage("FluentAssertions");
        }
    }

重點是
有回傳值可以直接
calculator.Add(1,2).Returns(x => { throw new Exception(); });

沒有回傳值就要用When Do的方式

如果不想用 
[ExpectedException(typeof(Exception))]
可以參考
NSubstitute 練習題 - 拋出 Exception
用上另一個好用的套件 FluentAssertions 就可以用
//act
Action act = () => calculator.Add(1, 2);
//assert
act.ShouldThrow<Exception>().WithMessage("FluentAssertions");

結語

之前覺得mrkt 的程式學習筆記的NSubstitute 練習題 - 拋出 Exception 寫得很清楚了
就沒打算寫這篇 不過後續
自己常常會需要用到解釋或忘記程式碼時
還是整理再這邊好了

如果內容有誤請多鞭策謝謝