运行测试,又会出现红条了,测试失败。现在要考虑实现一个真正的在数据库中的查找功能,怎么开始做呢?当然还是由测试开始,有了上面的基础,现在写的测试跨库可以稍微大点:
[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方法,而且上面的测试中已经包括了两个测试场景,现在可以直接写实现:
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;
}