Fiona - myaccessible.website Fiona - myaccessible.website - 3 months ago 60
C# Question

Moq and throwing a SqlException

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>();


However, this won't compile because SqlException's constructor is internal:


'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
'Moq.Language.IThrows.Throws()'


Now, I could change this to state that it should throw
Exception
, but that wouldn't work for me, because my method should return one status code if it is a
SqlException
and another if it is any other exception. That's what my unit test is testing.

Is there any way to achieve this without either changing the logic of the method I'm testing, or not testing this scenario?

Answer

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);

However, using 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).

Comments