How to throw a SqlException when needed for mocking and unit testing?

前端 未结 14 1695
孤街浪徒
孤街浪徒 2020-12-05 01:28

I am trying to test some exceptions in my project and one of the Exceptions I catch is SQlException.

It seems that you can\'t go new SqlException(

14条回答
  •  再見小時候
    2020-12-05 02:14

    This is really old and there are some good answers here. I am using Moq, and I can't mock up Abstract classes and really didn't want to use reflection, so I made my own Exception derived from DbException. So:

    public class MockDbException : DbException {
      public MockDbException(string message) : base (message) {}
    }   
    

    obviously, if you need to add InnerException, or whatever, add more props, constructors, etc.

    then, in my test:

    MyMockDatabase.Setup(q => q.Method()).Throws(new MockDbException(myMessage));
    

    Hoepfully this will help anyone that's using Moq. Thanks for everyone that posted in here that led me to my answer.

提交回复
热议问题