-
-
Save NaserKhoshfetrat/0fbe38718044ec56b7b66372a800bcaf to your computer and use it in GitHub Desktop.
Workaround completely test-unfriendly sql error classes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Data.SqlClient; | |
using System.Reflection; | |
namespace HorribleThingsInHere | |
{ | |
/// <summary> | |
/// Workaround completely test-unfriendly sql error classes. | |
/// Copy-paste from http://stackoverflow.com/a/1387030/10245 | |
/// Adjusted with updates in comments | |
/// </summary> | |
class SqlExceptionMocker | |
{ | |
private static T Construct<T>(int ctorIndex, params object[] p) | |
{ | |
var ctors = typeof (T).GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance); | |
var ctor = ctors[ctorIndex]; | |
return (T)ctor.Invoke(p); | |
} | |
public static SqlException MakeSqlException(int errorNumber) | |
{ | |
var collection = Construct<SqlErrorCollection>(0); | |
var error = Construct<SqlError>(1, errorNumber, (byte) 2, (byte) 3, "server name", "This is a Mock-SqlException", "proc", 100); | |
typeof (SqlErrorCollection) | |
.GetMethod("Add", BindingFlags.NonPublic | BindingFlags.Instance) | |
.Invoke(collection, new object[] {error}); | |
var e = typeof (SqlException) | |
.GetMethod("CreateException", BindingFlags.NonPublic | BindingFlags.Static, null, CallingConventions.ExplicitThis, new[] {typeof (SqlErrorCollection), typeof (string)}, new ParameterModifier[] {}) | |
.Invoke(null, new object[] {collection, "7.0.0"}) as SqlException; | |
return e; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment