Skip to content

Instantly share code, notes, and snippets.

@martinjw
Forked from timabell/SqlExceptionMocker.cs
Last active October 16, 2022 21:02
Show Gist options
  • Save martinjw/668700c8d199312dad7d to your computer and use it in GitHub Desktop.
Save martinjw/668700c8d199312dad7d to your computer and use it in GitHub Desktop.
Create a SqlException for testing
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
/// Adjusted to not use ctor indexes
/// </summary>
class SqlExceptionMocker
{
private static T Construct<T>(params object[] p)
{
var ctor = (from ctors in typeof(T).GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance)
where ctors.GetParameters().Count() == p.Count()
select ctors).Single();
return (T)ctor.Invoke(p);
}
public static SqlException MakeSqlException(int errorNumber)
{
var collection = Construct<SqlErrorCollection>();
var error = Construct<SqlError>(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;
}
}
}
@angularsen
Copy link

On .NET 4.7.2 I had to use this line:
var error = Construct<SqlError>(errorNumber, (byte) 2, (byte) 3, "server name", "This is a Mock-SqlException", "proc", 100, 0u);

There seems to be a new UInt32 parameter at the end.

@SharkInABottle
Copy link

Actually in .NET 4.8 , u need to add a new System.Exception() object type as parameter. it worked for me instead of UInt32 . I don't know may be there is a difference in System.Data package (nuget)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment