Monday, April 10, 2023

Unit testing with SqlException

Source:

https://blog.jonathanchannon.com/2014-01-02-unit-testing-with-sqlexception/

 

private SqlException GetSqlException()

{

    SqlErrorCollection collection = Construct<SqlErrorCollection>();

    SqlError error = Construct<SqlError>(-2, (byte)2, (byte)3, "server name", "error message", "proc", 100, (uint)1);


    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, "11.0.0" }) as SqlException;


    return e;

}


private T Construct<T>(params object[] p)

{

    return (T)typeof(T).GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance)[0].Invoke(p);

}