关闭

结合测试驱动TDD实施单元测试UnitTest

发表于:2011-7-08 12:59

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:未知    来源:51Testing软件测试网采编

  现在再运行之前的单元测试,会发现该单元测试已经顺利通过。大家是否看明白:单元测试只需要知道对被测试方法的期望值以及该方法可能依赖的项即可编写,无论这些方法是否已经真的实现。甚至可能的依赖项都是可以不用一开始编写的,而可以等到实现代码时发现需要调用其他方法时,再修改相应的单元测试代码进行隔离。

  在这里再多写一个例子,方便大家加深认识。这次对BaseOrderDetail上的Count方法编写单元测试。

/// <summary>
///A test for Count
///</summary>
[TestMethod()]
public void TestCount()
{
// Arrange
BaseOrderDetail target = new ClothingOrderDetail();
decimal expected = 1000.00m;
// Action
decimal actual = target.Count();
// Assert
Assert.AreEqual(expected, actual);
}

  这段代码是最简单的单元测试框架,如果执行肯定会因为Count方法还未实现而抛出异常。接下来我们编写Count方法的实现

/// <summary>
/// A abstract class of BaseOrderDetail.
/// </summary>
public abstract class BaseOrderDetail
{
/// <summary>
/// The identity of the current product.
/// </summary>
public Guid ProductID { get; set; }
/// <summary>
/// The amount of the current detail.
/// </summary>
public int Amount { get; set; }
/// <summary>
/// A third-part price provider.
/// </summary>
public IPriceProvide PriceProvider { get; set; }
/// <summary>
/// Count the totoal of the current oder detail
/// </summary>
/// <returns></returns>
public virtual decimal Count()
{
decimal result;
decimal price = this.PriceProvider.QueryPriceByProductID(this.ProductID);
result = price * this.Amount;
return result;
}
/// <summary>
/// A abstract class of BaseOrderDetail.
/// </summary>
public abstract class BaseOrderDetail
{
/// <summary>
/// The identity of the current product.
/// </summary>
public Guid ProductID { get; set; }
/// <summary>
/// The amount of the current detail.
/// </summary>
public int Amount { get; set; }
/// <summary>
/// A third-part price provider.
/// </summary>
public IPriceProvide PriceProvider { get; set; }
/// <summary>
/// Count the totoal of the current oder detail
/// </summary>
/// <returns></returns>
public virtual decimal Count()
{
decimal result;
decimal price = this.PriceProvider.QueryPriceByProductID(this.ProductID);
result = price * this.Amount;
return result;
}

53/5<12345>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号