-
-
Save chucksspencer/657cfef5f84f0c8cacf4613d96861ca7 to your computer and use it in GitHub Desktop.
Create a SqlException for testing
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
// .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, | |
null); | |
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; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment