现在再运行之前的单元测试,会发现该单元测试已经顺利通过。大家是否看明白:单元测试只需要知道对被测试方法的期望值以及该方法可能依赖的项即可编写,无论这些方法是否已经真的实现。甚至可能的依赖项都是可以不用一开始编写的,而可以等到实现代码时发现需要调用其他方法时,再修改相应的单元测试代码进行隔离。
在这里再多写一个例子,方便大家加深认识。这次对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; } |