Files
ScadaBridge/tests/ZB.MOM.WW.ScadaBridge.AuditLog.Tests/TestSupport/SqlExceptionFactory.cs
T

36 lines
1.8 KiB
C#

using System.Reflection;
using Microsoft.Data.SqlClient;
namespace ZB.MOM.WW.ScadaBridge.AuditLog.Tests.TestSupport;
/// <summary>
/// Fabricates a <see cref="SqlException"/> with a given error number via the driver's internal
/// <c>CreateException</c> factory (the type has no public constructor) — same technique as
/// ExternalSystemGateway.Tests' <c>FabricateSqlException</c>.
/// </summary>
internal static class SqlExceptionFactory
{
/// <summary>Creates a <see cref="SqlException"/> carrying one error with <paramref name="number"/>.</summary>
/// <param name="number">The SQL Server error number.</param>
/// <param name="message">The error message.</param>
/// <returns>The fabricated exception.</returns>
public static SqlException Create(int number, string message = "simulated")
{
var errorCtor = typeof(SqlError).GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic)
.First(c => c.GetParameters().Length == 8 && c.GetParameters()[7].ParameterType == typeof(Exception));
var sqlError = (SqlError)errorCtor.Invoke(
new object?[] { number, (byte)0, (byte)0, "server", message, "procedure", 0, null });
var collection = (SqlErrorCollection)typeof(SqlErrorCollection)
.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic).First()
.Invoke(Array.Empty<object?>());
typeof(SqlErrorCollection).GetMethod("Add", BindingFlags.Instance | BindingFlags.NonPublic)!
.Invoke(collection, new object?[] { sqlError });
var create = typeof(SqlException).GetMethod("CreateException",
BindingFlags.Static | BindingFlags.NonPublic,
new[] { typeof(SqlErrorCollection), typeof(string) })!;
return (SqlException)create.Invoke(null, new object?[] { collection, "6.0.0" })!;
}
}