问题描述
我有以下代码来测试当某个名称被传递给我的方法时,它会抛出一个 SQL 异常(这是有原因的,虽然听起来有点奇怪).
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>();
但是,这不会编译,因为 SqlException 的构造函数是内部的:
However, this won't compile because SqlException's constructor is internal:
'System.Data.SqlClient.SqlException' 必须是非抽象类型一个公共的无参数构造函数,以便将其用作参数泛型类型或方法中的TException"'Moq.Language.IThrows.Throws()'
现在,我可以更改它以声明它应该抛出 Exception
,但这对我不起作用,因为如果它是 SqlException 如果是任何其他异常,则为另一个.这就是我的单元测试正在测试的内容.
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?
推荐答案
这应该可行:
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
有这个警告:
However, using GetUninitializedObject
has this caveat:
因为对象的新实例被初始化为零并且没有构造函数运行时,对象可能不代表一个状态被该对象视为有效.
如果这会导致任何问题,您可能可以使用一些更复杂的反射魔法来创建它,但这种方式可能是最简单的(如果可行的话).
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).
这篇关于起订量并抛出 SqlException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!