運(yùn)行測試,又會出現(xiàn)紅條了,測試失敗,F(xiàn)在要考慮實現(xiàn)一個真正的在數(shù)據(jù)庫中的查找功能,怎么開始做呢?當(dāng)然還是由測試開始,有了上面的基礎(chǔ),現(xiàn)在寫的測試跨庫可以稍微大點:
[TestFixture]
public class CustomerDAOTests
{
[Test]
public void ShouldFoundCustomerByID()
{
string id = "ALFKI";
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方法,而且上面的測試中已經(jīng)包括了兩個測試場景,現(xiàn)在可以直接寫實現(xiàn):
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;
}
}
}
運(yùn)行一下該測試,通過!然后再將aspx.cs里面的代碼進(jìn)行改動使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;
}