Skip to content

Instantly share code, notes, and snippets.

@ShvedAction
Created September 20, 2016 09:16
Show Gist options
  • Save ShvedAction/592a77e9b45aab992c8a94b60493f940 to your computer and use it in GitHub Desktop.
Save ShvedAction/592a77e9b45aab992c8a94b60493f940 to your computer and use it in GitHub Desktop.
How to create the mock of SqlException for the unit test.
/// <summary>
/// Create SqlException for unit test(Reflection).
/// taken from: http://blog.gauffin.org/2014/08/how-to-create-a-sqlexception/
/// </summary>
/// <param name="number">This number will be at exception.number</param>
/// <param name="error_message">message</param>
/// <returns>new SqlException</returns>
private SqlException CreateSqlException(int number, string error_message = "the mock error 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,
null,
new[] { typeof(string), typeof(SqlErrorCollection), typeof(Exception), typeof(Guid) },
null);
return (SqlException)constructor.Invoke(new object[] { error_message , errorCollection, new DataException(), Guid.NewGuid() });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment