【发布时间】:2012-02-11 12:19:52
【问题描述】:
我一直在努力解决单元测试问题,并且我正在尝试处理一个函数的单元测试,该函数的返回值取决于一堆参数。但是信息量很大,有点不知所措..
考虑以下几点:
我有一个类Article,它有一个价格集合。它有一个方法GetCurrentPrice,它根据一些规则确定当前价格:
public class Article
{
public string Id { get; set; }
public string Description { get; set; }
public List<Price> Prices { get; set; }
public Article()
{
Prices = new List<Price>();
}
public Price GetCurrentPrice()
{
if (Prices == null)
return null;
return (
from
price in Prices
where
price.Active &&
DateTime.Now >= price.Start &&
DateTime.Now <= price.End
select price)
.OrderByDescending(p => p.Type)
.FirstOrDefault();
}
}
PriceType 枚举和 Price 类:
public enum PriceType
{
Normal = 0,
Action = 1
}
public class Price
{
public string Id { get; set; }
public string Description { get; set; }
public decimal Amount { get; set; }
public PriceType Type { get; set; }
public DateTime Start { get; set; }
public DateTime End { get; set; }
public bool Active { get; set; }
}
我想为GetCurrentPrice 方法创建一个单元测试。基本上我想测试所有可能出现的规则组合,所以我必须创建多篇文章来包含各种价格组合才能获得全面覆盖。
我正在考虑这样的单元测试(伪):
[TestMethod()]
public void GetCurrentPriceTest()
{
var articles = getTestArticles();
foreach (var article in articles)
{
var price = article.GetCurrentPrice();
// somehow compare the gotten price to a predefined value
}
}
我读过“多个断言是邪恶的”,但我不需要 他们在这里测试所有条件?或者我需要一个单独的单元 按条件测试?
如何为单元测试提供一组测试数据? 我应该模拟存储库吗?如果这些数据还包括 期望值?
【问题讨论】:
标签: c# unit-testing mocking