多输入unit testing

我一直在尝试围绕unit testing,我正在尝试处理unit testing一个函数,其返回值取决于一堆参数。 然而,有很多信息,它有点压倒性的..

考虑以下:

我有一篇Article ,其中有一组价格。 它有一个方法GetCurrentPrice ,它根据一些规则确定当前价格:

 public class Article { public string Id { get; set; } public string Description { get; set; } public List Prices { get; set; } public Article() { Prices = new List(); } public Price GetCurrentPrice() { if (Prices == null) return null; return ( from price in Prices where price.Active && DateTime.Now >= price.Start && DateTime.Now  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方法创建一个unit testing。 基本上我想测试可能发生的所有规则组合,因此我必须创建多个文章以包含各种价格组合以获得完全覆盖。

我正在考虑像这样的unit testing(伪):

 [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 } } 
  • 我已经读到“多个断言是邪恶的”,但是我不需要它们来测试这里的所有条件吗? 或者我是否需要根据条件单独进行unit testing?

  • 我如何为unit testing提供一组测试数据? 我应该模拟存储库吗? 这些数据是否还包括预​​期值?

您没有在此示例中使用存储库,因此无需模拟任何内容。 您可以做的是为不同的输入创建多个unit testing:

 [TestMethod] public void Foo() { // arrange var article = new Article(); // TODO: go ahead and populate the Prices collection with dummy data // act var actual = article.GetCurrentPrice(); // assert // TODO: assert on the actual price returned by the method // depending on what you put in the arrange phase you know } 

等等,您可以添加其他unit testing,您只需更改每个可能输入的arrangeassert阶段。

您不需要多个断言。 您需要多个测试,每个测试只有一个断言。

每个启动条件的新测试和单个断言,fe

 [Test] public void GetCurrentPrice_PricesCollection1_ShouldReturnNormalPrice(){...} [Test] public void GetCurrentPrice_PricesCollection2_ShouldReturnActionPrice(){...} 

并测试边界

对于unit testing,我使用模式

 MethodName_UsedData_ExpectedResult() 

我认为你需要进行数据驱动测试。 在vsts中有一个名为Datasource的属性,使用它可以发送一个测试方法多个测试用例。 确保不要使用多个断言。 这是一个MSDN链接http://msdn.microsoft.com/en-us/library/ms182527.aspx

希望这会帮助你。