起订量并抛出 SqlException

Moq and throwing a SqlException(起订量并抛出 SqlException)
本文介绍了起订量并抛出 SqlException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有以下代码来测试当某个名称被传递给我的方法时,它会抛出一个 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()'

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

现在,我可以更改它以声明它应该抛出 Exception,但这对我不起作用,因为如果它是 SqlException<,我的方法应该返回一个状态码/code> 如果是任何其他异常,则为另一个.这就是我的单元测试正在测试的内容.

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:

因为对象的新实例被初始化为零并且没有构造函数运行时,对象可能不代表一个状态被该对象视为有效.

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

这篇关于起订量并抛出 SqlException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to MOQ an Indexed property(如何最小起订量索引属性)
Mocking generic methods in Moq without specifying T(在 Moq 中模拟泛型方法而不指定 T)
How Moles Isolation framework is implemented?(Moles Isolation 框架是如何实现的?)
Difference between Dependency Injection and Mocking Framework (Ninject vs RhinoMocks or Moq)(依赖注入和模拟框架之间的区别(Ninject vs RhinoMocks 或 Moq))
How to mock Controller.User using moq(如何使用 moq 模拟 Controller.User)
How do I mock a class without an interface?(如何模拟没有接口的类?)