尝试使用WatiN进行TDD(2)

发表于:2014-12-16来源:uml.org.cn作者:Bluse Huang点击数: 标签:tdd
string comName = Alfreds Futterkiste; CustomerDAO customerDAO = new CustomerDAO(); Customer found = customerDAO.FindCustomerByID(id); Assert.That(found, Is.Not.Null); Assert.That(found.CustomerID, Is.

  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