string comName = "Alfreds Futterkiste";
CustomerDAO customerDAO = new CustomerDAO();
Customer found = customerDAO.FindCustomerByID(id);
Assert.That(found, Is.Not.Null);
Assert.That(found.CustomerID, Is.EqualTo(id));
Assert.That(found.CompanyName, Is.EqualTo(comName));
id = "AROUT";
comName = "Around the Horn";
found = customerDAO.FindCustomerByID(id);
Assert.That(found, Is.Not.Null);
Assert.That(found.CustomerID, Is.EqualTo(id));
Assert.That(found.CompanyName, Is.EqualTo(comName));
}
}
這段代碼不能編譯,因為并沒有CustomerDAO這個類,所以得新增該類以及FindCustomerByID方法,而且上面的測試中已經包括了兩個測試場景,現在可以直接寫實現:
public class CustomerDAO
{
public Customer FindCustomerByID(string id)
{
using (NorthwindDataContext ctx = new NorthwindDataContext())
{
IQueryable customers = ctx.Customers.Where(c => c.CustomerID == id);
if (customers.Count() > 0)
return customers.Single();
else
return null;
}
}
}
運行一下該測試,通過!然后再將aspx.cs里面的代碼進行改動使Web頁面的測試通過
void btn_find_customer_Click(object sender, EventArgs e)
{
string id = tb_customerID.Text;
Customer c = customerDAO.FindCustomerByID(id);
if (c == null)
return;
lbl_customerID.Text = c.CustomerID;
lbl_companyName.Text = c.CompanyName;
pnl_customerInfo.Visible = true;
}
不錯,現在第一部分功能已經完成了,所有測試已經通過了,這時候我們可以打開瀏覽器,試試查找Customer的功能。
回頭看看剛才寫的測試代碼,有很多重復的地方,這是不好的,需要進行重構。這里也就不列出重構代碼了。
到我們實現第二部分的時候了,列出該用戶相關的所有Order。在這里也不再詳細些步驟了,就放出測試代碼,實現的話還是很容易的 :) 當然測試并不完全,需要更加完善。
web頁面測試代碼:
[Test]
public void ShouldFindOrders()
{
string id = "ALFKI";
ie.TextField(Find.ById("tb_customerID")).TypeText(id);
ie.Button(Find.ById("btn_find_customer")).Click();
ie.Button(Find.ById("btn_find_orders")).Click();
Table ordersTable = ie.Table(Find.ById("grdv_orders"));
Assert.That(ordersTable, Is.Not.Null);
Assert.That(ordersTable.TableRows.Length, Is.EqualTo(6 + 1));
}
DAO測試代碼:
[TestFixture]
public class OrderDAOTests
{
[Test]
public void ShouldFindOrdersByCustomerID()
{
string id = "ALFKI";
OrderDAO orderDAO = new OrderDAO();
List orders = orderDAO.FindOrdersByCustomerID(id);
Assert.That(orders.Count, Is.EqualTo(6));
}
}
原文轉自:http://www.uml.org.cn/Test/200805236.asp