正确模拟SQLConnection
我正在尝试模拟以下方法,
public static object ExecuteGetObj(string query)
{
object obj = null;
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Default"].ConnectionString))
{
connection.Open();
using (SqlCommand cmd = new SqlCommand(query, connection))
{
obj = cmd.ExecuteScalar();
}
}
return obj;
}
但它不是使用模拟SQLConnection,而是尝试创建SQLConnection
var command = new Mock<IDbCommand>();
command.Setup(x => x.ExecuteScalar())
.Verifiable();
var connection = new Mock<IDbConnection>();
connection
.Setup(m => m.CreateCommand())
.Returns(command.Object);
connection.Object.Open();
var obj = Common.ExecuteGetObj(sql);
Assert.IsNull(obj);
I am trying to mock the below method,
public static object ExecuteGetObj(string query)
{
object obj = null;
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Default"].ConnectionString))
{
connection.Open();
using (SqlCommand cmd = new SqlCommand(query, connection))
{
obj = cmd.ExecuteScalar();
}
}
return obj;
}
but it is not using the Mock SqlConnection instead it is trying to create the SqlConnection
var command = new Mock<IDbCommand>();
command.Setup(x => x.ExecuteScalar())
.Verifiable();
var connection = new Mock<IDbConnection>();
connection
.Setup(m => m.CreateCommand())
.Returns(command.Object);
connection.Object.Open();
var obj = Common.ExecuteGetObj(sql);
Assert.IsNull(obj);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您只能模拟
抽象类
或接口
,因此这是行不通的。此代码实例化
sqlConnection
,您在测试中设置了mock&lt; iDbConnection&gt;
无处可使用。如果您绝对要要单位测试此代码,则代码本身需要更改;它需要通过iDbConnection
以某种方式,无论是作为构造函数参数(您需要具有非static> static
类)还是作为方法本身的参数,然后可以模拟。我会推荐针对 单位测试 您要解决什么问题?通常被认为不良练习更改代码只是为了能够更改代码测试它。如果您想测试这个问题,则可以考虑集成测试;如果此代码属于API的一部分,则可以(例如)在该级别上进行终点测试。
You can only mock either
abstract classes
orinterfaces
, so this is not going to work.This code instantiates a
SqlConnection
, nowhere does it use theMock<IDbConnection>
you setup in the test. If you absolutely do want to unit test this code, the code itself needs to change; it needs to be passed aIDbConnection
somehow, whether as a constructor argument (you need to have a nonstatic
class) or as an argument to the method itself, which you then can mock.I would recommend against unit testing this method though, what problem are you trying to solve? It is generally considered bad practice to change code just to be able to test it. If you want to test this, you could look into integrating testing; if this code is part of an API you could (for instance) do end to end testing on that level.