可测试性驱动开发的一个不严谨例子
一个购物车的例子
public class Cart
{
public Logger logger = new Logger();
public List<Product> ProductList;
public Cart()
{
ProductList = new List<Product>();
}
{
public Logger logger = new Logger();
public List<Product> ProductList;
public Cart()
{
ProductList = new List<Product>();
}
public int GetTotalCount()
{
return this.ProductList.Count;
}
{
return this.ProductList.Count;
}
public void Add(Product product)
{
//小记下log
logger.Log(string.Format("添加了一件商品"));
//一大段逻辑
Console.WriteLine("判断是否重复");
Console.WriteLine("判断商品ID是不是正确");
ProductList.Add(product);
}
}
logger一开始是这样的
public class Logger
{
//插入数据库
public void Log(string message)
{
Console.WriteLine(string.Format("插入数据库:{0}",message));
}
}
{
//插入数据库
public void Log(string message)
{
Console.WriteLine(string.Format("插入数据库:{0}",message));
}
}
测试代码,但是。。。为了测试还要写数据库吗?我只是想测试下购物车的逻辑呃。。。
[TestMethod()]
public void AddTest()
{
Cart cart = new Cart();
// TODO: Initialize to an appropriate value
Product product = new Product();
cart.Add(product);
Assert.AreEqual<int>(1,cart.GetTotalCount());
}
public void AddTest()
{
Cart cart = new Cart();
// TODO: Initialize to an appropriate value
Product product = new Product();
cart.Add(product);
Assert.AreEqual<int>(1,cart.GetTotalCount());
}
开始可测试性重构
public interface ILog
{
void Log(string message);
}
public class Logger:ILog
{
//插入数据库
public void Log(string message)
{
Console.WriteLine(string.Format("插入数据库:{0}",message));
}
}
{
void Log(string message);
}
public class Logger:ILog
{
//插入数据库
public void Log(string message)
{
Console.WriteLine(string.Format("插入数据库:{0}",message));
}
}
测试代码修改
public ILog logger;
public Cart(ILog logger)
{
ProductList = new List<Product>();
this.logger = logger;
}
public Cart(ILog logger)
{
ProductList = new List<Product>();
this.logger = logger;
}
public class MemLog : ILog
{
public void Log(string message)
{
Console.WriteLine("记内存下就好");
}
}
[TestMethod()]
public void AddTest()
{
Cart cart = new Cart(new MemLog()); Product product = new Product();
cart.Add(product);
Assert.AreEqual<int>(1,cart.GetTotalCount());
}
{
public void Log(string message)
{
Console.WriteLine("记内存下就好");
}
}
[TestMethod()]
public void AddTest()
{
Cart cart = new Cart(new MemLog()); Product product = new Product();
cart.Add(product);
Assert.AreEqual<int>(1,cart.GetTotalCount());
}