插入命令的单元测试

时间:2016-05-04 08:26:11

标签: c# mysql sql database unit-testing

我是单元测试的新手,我需要在我的代码中测试一个insert命令。任何人都可以让我知道该怎么做..以下是我想测试的方法。

    public void InsertData()
    {        
        Connect();    
        query = "Insert into Person values ('"+ name +"','"+ address +"','"+ 
        phn +"')";            
        cmd = new SqlCommand(query, Conn);                      
        cmd.ExecuteNonQuery();
        DisConnect();
    }

1 个答案:

答案 0 :(得分:2)

目前您的方法无法测试。应避免所有对实际数据的引用。

这将是一个重构的方法:

public interface IDbContext
{
    void Connect();
    void DisConnect();
    IDbCommand GetDbCommand(string query, string[] parameters);
}

public class DbContext : IDbContext
{
    public IDbConnection Conn { get; set; }

    public void Connect()
    {
        // your code here
    }

    public void DisConnect()
    {
        // your code here
    }

    public IDbCommand GetDbCommand(string query, string[] parameters)
    {
        // parameter handling
        return new SqlCommand(query, (SqlConnection)Conn);
    }
}

public class YourClass
{
    private string name;
    private string address;
    private string phn;

    public void InsertData(IDbContext context)
    {
        context.Connect();
        var cmd = context.GetDbCommand("Insert into Person values ('{0}','{1}','{2}')", new string[] { name, address, phn });
        cmd.ExecuteNonQuery();
        context.DisConnect();
    }
}

要测试这个,你可以这样做:

[TestClass]
public class TestClass
{
    [TestMethod]
    public void TestMethod1()
    {
        var instance = new YourClass();

        // create an instance of IDbContext
        var context = new Mock<IDbContext>();
        // create an instance of IDbCommand
        var command = new Mock<IDbCommand>();

        // setup your context and what should be the return of any method you want
        context.Setup(c => c.GetDbCommand(It.IsAny<string>(), It.IsAny<string[]>())).Returns(command.Object);

        // call your method you want to test
        instance.InsertData(context.Object);

        // assert that context methods ar called
        context.Verify(c => c.Connect(), Times.Once);
        context.Verify(c => c.DisConnect(), Times.Once);
        context.Verify(c => c.GetDbCommand(It.IsAny<string>(), It.IsAny<string[]>()), Times.Once);

        // assert that command methods ar called
        command.Verify(c => c.ExecuteNonQuery(), Times.Once);
    }
}