I have the following code to test that when a certain name is passed to my method, it throws a SQL exception (there is reason to that one, although it sounds a little odd).
mockAccountDAL.Setup(m => m.CreateAccount(It.IsAny<string>(),
"Display Name 2", It.IsAny<string>())).Throws<SqlException>();
'System.Data.SqlClient.SqlException' must be a non-abstract type with
a public parameterless constructor in order to use it as parameter
'TException' in the generic type or method
This should work:
using System.Runtime.Serialization; var exception = FormatterServices.GetUninitializedObject(typeof(SqlException)) as SqlException; mockAccountDAL.Setup(m => m.CreateAccount(It.IsAny<string>(), "Display Name 2", It.IsAny<string>())).Throws(exception);
GetUninitializedObject has this caveat:
Because the new instance of the object is initialized to zero and no constructors are run, the object might not represent a state that is regarded as valid by that object.
If this causes any problems, you can probably create it using some more involved reflection magic but this way is probably the simplest (if it works).