我如何存根 IDBconnection

How can I stub IDBconnection

我正在为我的数据库连接编写单元测试。

我关注class

Public class A
{
    public IDbConnection _dbConnection;

    public A()
    {
       _dbConnection = new SqlConnection(connectionStringName);
    }

    public int ExecuteNoneQuery(CommandDefination command)
    {
       return _dbConnection.Execute(command);
    }
}

我想测试这个 class,如何使用 Microsoft 进行测试 Stub/Shim

我写了下面的代码,但是没有用。

[TestMethod]
public void TestMethod1()
{
    StubIDbConnection stubIDbConnection = new StubIDbConnection();
    stubIDbConnection.Execute =(null) => -1;
    var a = new classA();
    int answer = a.ExecuteNoneQuery(null);
    Assert.AreEqual(-1, answer);

 }

方法 execute 在 IDbConnection / SqlConnection 中不存在。因此,我假设您已经创建了自定义界面和 class.

测试代码的正确方法是将代码更改为 "code that designed to be a testable":

public class A
{
    public IDbConnection _dbConnection;

    public A() : this(new SqlConnection()){}

    public A(IDbConnection connection)
    {
        _dbConnection = connection;
    }
}

现在你可以注入你的假连接了:

[TestMethod]
public void TestMethod1()
{
    StubIDbConnection stubIDbConnection = new StubIDbConnection();
    stubIDbConnection.Execute =(null) => -1;
    var a = new classA(stubIDbConnection);
    int answer = a.ExecuteNoneQuery(null);
    Assert.AreEqual(-1,-1);
}

如果您不想更改代码。您必须创建shim,然后更改您的测试方法:

    [TestMethod]
    public void TestMethod1()
    {
        using (ShimsContext.Create())
        {
            System.Data.SqlClient.Fakes.ShimSqlConnection.AllInstances.Execute = 
            (connection, command) =>
            {
                if (command != null)
                    throw new Exception("command is not null");

                return -1;
            };

            var a = new classA();
            int answer = a.ExecuteNoneQuery(null);
            Assert.AreEqual(-1, -1);
        }
    }

编辑

出现您遇到的问题是因为 Execute 方法有多个重载。

将您的测试方法更改为:

    [TestMethod]
    public void TestMethod1()
    {
        using (ShimsContext.Create())
        {
            Dapper.Fakes.ShimSqlMapper.ExecuteIDbConnectionCommandDefinition =
                (connection, command) =>
                {
                    //add here params verification...

                    return -1;
                };

            var a = new A();
            int answer = a.ExecuteNoneQuery(new CommandDefinition());
            Assert.AreEqual(-1, answer);
        }
    }

您可以轻松地使用 class A 的构造函数来插入您的依赖项,将以下构造函数添加到 class A:

public A(IDBConnection connection)
{
   _dbConnection = connection;
}

那么您的测试将如下所示:

[TestMethod]
public void TestMethod1()
{
    StubIDbConnection stubIDbConnection = new StubIDbConnection();
    stubIDbConnection.Execute =(null) => -1;
    var a = new classA(stubIDbConnection);
    int answer = a.ExecuteNoneQuery(null);
    Assert.AreEqual(-1,answer);
}