How to throw SqlException when you need it in Test
You can do this with reflection, you will have to maintain it when Microsoft make changes, but it does work I just tested:
internal class SqlExceptionTestHelper
{
public static T Construct<T>(params object[] p)
{
return (T)typeof(T).GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance)[0].Invoke(p);
}
public static SqlException GenerateSqlException()
{
SqlErrorCollection collection = Construct<SqlErrorCollection>();
//2627 means error number
SqlError error = Construct<SqlError>(2627, (byte)2, (byte)3, "server name", "error message", "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)
.Invoke(null, new object[] { collection, "7.0.0" }) as SqlException;
return e;
}
And then, the code about throw SqlException is like this:
"throw SqlExceptionTestHelper.GenerateSqlException()"
参考:http://stackoverflow.com/questions/1386962/how-to-throw-a-sqlexceptionneed-for-mocking
How to throw a SqlException(need for mocking)
Unit Testing with SqlException in .NET: Only with help from Reflection

浙公网安备 33010602011771号