1、写单元测试使他亮红灯
2、写代码使测试变成绿灯
3、重构代码
接下来我们需要开始重构了,大家有可能会问,为什么需要重构,什么时候开始重构。
对与为什么需要重构,其实就是为了使代码结构清晰,去除一些重复的代码,比如我们执行sql语句操作,我们起初这样写:
Code
1private connStr="server=.;database=TestDB;uid=sa;pwd=123"
2public int Add(string loginName)
3{
4 int count = 0;
5 using (SqlConnection conn = new SqlConnection(connStr))
6 {
7 conn.Open();
8 SqlCommand cmd = new SqlCommand("insert(loginName) value('" + loginName + "')", conn);
9 count = cmd.ExecuteNonQuery();
10 cmd.Dispose();
11 conn.Close();
12 }
13 return count;
14}
15
16public int Delete(string loginName)
17{
18 int count = 0;
19 using (SqlConnection conn = new SqlConnection(connStr))
20 {
21 conn.Open();
22 SqlCommand cmd = new SqlCommand("delete from LoginUsers where loginName='" + loginName + "'", conn);
23 count = cmd.ExecuteNonQuery();
24 cmd.Dispose();
25 conn.Close();
26 }
27 return count;
28}
1private int ExecuteSql(string sql)
2{
3 int count = 0;
4 using (SqlConnection conn = new SqlConnection(connStr))
5 {
6 conn.Open();
7 SqlCommand cmd = new SqlCommand(sql, conn);
8 count = cmd.ExecuteNonQuery();
9 cmd.Dispose();
10 conn.Close();
11 }
12 return count;
13}
14public int Add(string loginName)
15{
16 return ExecuteSql("insert(loginName) value('" + loginName + "')");
17}
18public int Delete(string loginName)
19{
20 return ExecuteSql("delete from LoginUsers where loginName='" + loginName + "'");
21}
文章来源于领测软件测试网 https://www.ltesting.net/