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

前端 未结 14 1683
孤街浪徒
孤街浪徒 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:23

    You could use reflection to create SqlException object in the test:

            ConstructorInfo errorsCi = typeof(SqlErrorCollection).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[]{}, null);
            var errors = errorsCi.Invoke(null);
    
            ConstructorInfo ci = typeof(SqlException).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof(string), typeof(SqlErrorCollection) }, null);
            var sqlException = (SqlException)ci.Invoke(new object[] { "Exception message", errors });
    

提交回复
热议问题