Moq和SqlConnection? [英] Moq and SqlConnection?

查看:69
本文介绍了Moq和SqlConnection?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我们的一种产品编写单元测试,并已被Moq用来成功模拟到Entity Framework的连接.但是,我遇到了以下方法:

I'm writing unit tests for one of our products and have been used Moq to successfully mock connections to Entity Framework. However, I've come across the following method:

public static productValue findValues(string productName, string dbConnectionString)
{
    try
    {
        SqlConnection conn = new SqlConnection(dbConnectionString);
        conn.Open();
        //Do stuff 
    }
}

使用传递的连接字符串在该方法内访问我们的数据库.是否可以使用Moq设置模拟数据库并创建指向模拟数据库的连接字符串?我正在尝试按照以下方式进行操作

Which accesses our database inside that method using a passed connection string. Is it possible to setup a mock DB using Moq and create a connection string which points to the mocked DB? I've trying doing something along the lines of

var mockSqlConnnection = new Mock<SqlConnection>();

尽管我不确定这是否是正确的方法,因为这会模拟连接本身而不是数据库.

Though I'm unsure if this is the correct approach, as this would mock the connection itself rather than the DB.

推荐答案

我遇到了类似的问题.

I had a similar problem.

我在SqlConnection周围引入了SqlDataContext包装器,该包装器继承自和ISqlDataContext接口:

I introduced an SqlDataContext wrapper around the SqlConnection which inherited from and ISqlDataContext interface:

class SqlDataContext : ISqlDataContext {

    private readonly SqlConnection _connection;

    public SqlDataContext(string connectionString)
    {
        _connection = CreateConnection(connectionString);
    }

    public IDataReader ExecuteReader(string storedProcedureName, ICollection<SqlParameter> parameters)
    {
       // execute the command here using the _connection private field.
       // This is where your conn.Open() and "do stuff" happens.
    }

    private SqlConnection CreateConnection(string connectionString)
    {
        if (string.IsNullOrEmpty(connectionString))
        {
            throw new ArgumentNullException("connectionString");
        }

        return new SqlConnection(connectionString);
    }
}

interface ISqlDataContext
{
    IDataReader ExecuteReader(string storedProcedureName, ICollection<SqlParameter> parameters);
}

您可以根据需要向ISqlDataContext添加重载.

You can add overloads to the ISqlDataContext as you need.

这意味着您可以根据需要使用Moq或类似方法模拟ISqlDataContext并返回模拟值.

What this means is that you can then mock the ISqlDataContext as requires using Moq or similar and return mock values.

意味着您可以测试存储库或通过SqlConnection命中数据库的任何其他事物,而无需实际命中数据库.

Means you can then test your repository or anything else that hits the database through the SqlConnection without actually having to hit the database.

另一个优点是您可以根据需要使用I/C注入ISqlContext.

The other advantage is that you can inject ISqlContext with DI / IoC as needed.

这篇关于Moq和SqlConnection?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆