Skip to content

Instantly share code, notes, and snippets.

@Boggin
Forked from martinjw/SqlExceptionMocker.cs
Last active November 9, 2018 17:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Boggin/7f5df031ec34d8fa2145739705031340 to your computer and use it in GitHub Desktop.
Save Boggin/7f5df031ec34d8fa2145739705031340 to your computer and use it in GitHub Desktop.
Create a SqlException for testing
// .csproj
// <PackageReference Include="System.Data.SqlClient" Version="4.3.0" />
// <PackageReference Include="System.Reflection.TypeExtensions" Version="4.3.0" />
namespace HorribleThingsInHere
{
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
/// <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",
new[] { typeof (SqlErrorCollection), typeof (string) })
.Invoke(null, new object[] {collection, "7.0.0"}) as SqlException;
return e;
}
}
}
@Boggin
Copy link
Author

Boggin commented Mar 21, 2017

This compiles now but will fail in dotnet-core.

@chucksspencer
Copy link

Fix for dotnet-core is to add one more null param to the Construct call on line 33. I made a fork with the change.

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