在按钮中调用功能进行单元测试


private void btnSave_Click(object sender, EventArgs e)
    {
        if(txtFirstName.Text.Trim() != "" && txtLastName.Text.Trim() != "" && txtContact.Text.Trim() != "")
        {
            Regex reg = new Regex(@"^([w.-]+)@([w-]+)((.(w){2,3})+)$"); //only accepting proper email
            Match match = reg.Match(txtEmail.Text.Trim());
            if (match.Success)
            { using (SqlConnection sqlCon = new SqlConnection(connectionString)) // connecting info to database
                {
                    sqlCon.Open();
                    SqlCommand sqlCmd = new SqlCommand("ContactAddorEdit", sqlCon);
                    sqlCmd.CommandType = CommandType.StoredProcedure;
                    sqlCmd.Parameters.AddWithValue("@PhoneBookID", PhoneBookID); //connecting each value to database
                    sqlCmd.Parameters.AddWithValue("@FirstName", txtFirstName.Text.Trim());
                    sqlCmd.Parameters.AddWithValue("@LastName", txtLastName.Text.Trim());
                    sqlCmd.Parameters.AddWithValue("@Contact", txtContact.Text.Trim());
                    sqlCmd.Parameters.AddWithValue("@Email", txtEmail.Text.Trim());
                    sqlCmd.Parameters.AddWithValue("@Address", txtAddress.Text.Trim());
                    sqlCmd.ExecuteNonQuery(); // executeing the query in database
                    MessageBox.Show("Submitted successfully"); // showing message when success
                    Clear(); // clearing the form
                    GridFill();// refreshing the table
                }
            }
            else
            {
                MessageBox.Show(" Please enter a valid Email"); // Showing MEssage when email is not valid
            }
        }
        else
        {
            MessageBox.Show("Please fill Mandatory fields"); // if no input this message will show
        }

这些代码位于表单中的"保存"按钮下,我想在单元测试类中调用它们以进行测试。知道我该怎么办?谢谢

首先,恭喜您试图弄清楚如何编写单元测试。将代码隔离到可测试单元中是一种习惯,可导致各种出色的模式。

关于我们如何设置这样的东西有很多想法,但是我将在这里放置的只是隔离测试代码的一些步骤,而无需更改代码本身。

我不会停止这一点 - 实际上,在阅读和了解更多信息后的短时间内,您可能会选择一些更好的技术。我觉得有必要指出这一点,因为我在这里描述的是一个步骤,而不是最终目的地。

首先,您可以将SQL代码移至这样的类:

public class SqlCommands
{
    private readonly string _connectionString;
    public SqlCommands(string connectionString)
    {
        _connectionString = connectionString;
    }
    public void InsertUpdateContact(InsertUpdateContactParameters parameters)
    {
        using (SqlConnection sqlCon = new SqlConnection(_connectionString)) 
        {
            sqlCon.Open();
            SqlCommand sqlCmd = new SqlCommand("ContactAddorEdit", sqlCon);
            sqlCmd.CommandType = CommandType.StoredProcedure;
            sqlCmd.Parameters.AddWithValue("@PhoneBookID", parameters.PhoneBookId); //connecting each value to database
            sqlCmd.Parameters.AddWithValue("@FirstName",parameters.FirstName);
            sqlCmd.Parameters.AddWithValue("@LastName",parameters.LastName);
            sqlCmd.Parameters.AddWithValue("@Contact",parameters.Contact);
            sqlCmd.Parameters.AddWithValue("@Email", parameters.Email);
            sqlCmd.Parameters.AddWithValue("@Address",parameters.Address);
            sqlCmd.ExecuteNonQuery();
        }
    }
}
public class InsertUpdateContactParameters
{
    public int PhoneBookId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Contact { get; set; }
    public string Email { get; set; }
    public string Address { get; set; }
}

作为第一步,您可以在表单中创建SqlCommands类的实例,然后调用InsertUpdateContact,以从您的表单字段填充的参数传递。这使您可以为您可以执行的SQL代码创建测试而无需打开表单,输入值并按下按钮。

您的SQL代码的测试在技术上不是单位测试,因为它与您的数据库进行了对话。这是一个集成测试。但是看起来和功能就像单位测试一样。你要去

  • 安排 - 设置一些东西
  • ACT-执行您的方法
  • 断言 - 如果您期望发生的事情,您的测试会通过,否则会失败。

对于真正的简单测试,您可以

  • 安排 - 从表中删除与某些模式相匹配的所有记录,例如电子邮件地址为" IntegrationTest@integrationTest.com"之类的。
  • ACT-调用您的方法,传递一组值,包括您刚刚删除的相同电子邮件地址。
  • 断言 - 查询您的数据库以确认其包含符合您刚插入的值的记录。
  • 清理 - 为了良好的措施,再次运行删除,这样您就不会抛弃测试记录。

使插入和删除更容易,您可以在单元测试项目中放入类:

static class Sql
{
    public static void ExecuteSql(string connectionName, string sql)
    {
        using (var connection = new SqlConnection(GetConnectionString(connectionName)))
        {
            using (var command = new SqlCommand(sql, connection))
            {
                connection.Open();
                command.ExecuteNonQuery();
            }
        }
    }
    public static T ExecuteScalar<T>(string connectionName, string sql)
    {
        using (var connection = new SqlConnection(GetConnectionString(connectionName)))
        {
            using (var command = new SqlCommand(sql, connection))
            {
                connection.Open();
                return (T)command.ExecuteScalar();
            }
        }
    }
    public static string GetConnectionString(string connectionName)
    {
        return ConfigurationManager.ConnectionStrings[connectionName].ConnectionString;
    }
}

如果您使用的是.NET框架,则可以使用一个app.config文件,其中包含这样的连接字符串部分:

<connectionStrings>
  <add name="yourDatabaseName" connectionString="whatever your connection string is" 
   providerName="System.Data.SqlClient" />
</connectionStrings>

,或者您可以编码它以根据存储来检索连接字符串。

允许您在测试中编写代码,例如

Sql.ExecuteSql("Your connection name", "SQL to delete records");

var numberOfInsertedRecords = Sql.ExecuteScalar<int>("Your connection name",
    "SELECT COUNT(*) FROM Whatever WHERE ... " 
    + "Replace with criteria that checks for the record you just inserted."

然后在您的测试中您可以说:

Assert.AreEqual(1, numberOfInsertedRecords);

您可能想阅读的其他一些有趣的领域是依赖注入,ORM(例如实体框架和NHIBERNATE)和CQR。这是很多要堆积的东西,但是如果您只是开始编写表格和一些SQL,并且已经在考虑单元测试,那么天空是极限。


这是我几年前写的一篇博客文章。感觉过时了。我很不得不为几乎一两年前写过的任何东西道歉。

最新更新