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(
I suggest using this method.
///
/// Method to simulate a throw SqlException
///
/// Exception number
/// Exception message
///
public static SqlException CreateSqlException(int number, string message)
{
var collectionConstructor = typeof(SqlErrorCollection)
.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, //visibility
null, //binder
new Type[0],
null);
var addMethod = typeof(SqlErrorCollection).GetMethod("Add", BindingFlags.NonPublic | BindingFlags.Instance);
var errorCollection = (SqlErrorCollection)collectionConstructor.Invoke(null);
var errorConstructor = typeof(SqlError).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null,
new[]
{
typeof (int), typeof (byte), typeof (byte), typeof (string), typeof(string), typeof (string),
typeof (int), typeof (uint)
}, null);
var error =
errorConstructor.Invoke(new object[] { number, (byte)0, (byte)0, "server", "errMsg", "proccedure", 100, (uint)0 });
addMethod.Invoke(errorCollection, new[] { error });
var constructor = typeof(SqlException)
.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, //visibility
null, //binder
new[] { typeof(string), typeof(SqlErrorCollection), typeof(Exception), typeof(Guid) },
null); //param modifiers
return (SqlException)constructor.Invoke(new object[] { message, errorCollection, new DataException(), Guid.NewGuid() });
}