gpt4 book ai didi

c# - 具有多个输入的单元测试

转载 作者:行者123 更新时间:2023-11-30 13:40:00 25 4
gpt4 key购买 nike

我一直在努力全神贯注于单元测试,并且我正在尝试对返回值取决于一组参数的函数进行单元测试。然而,有很多信息,而且有点让人不知所措..

考虑以下几点:

我有一个 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
}
}
  • 我读过“多重断言是邪恶的”,但我不需要他们来测试这里的所有条件?或者我需要一个单独的单元按条件测试?

  • 我将如何为单元测试提供一组测试数据?我应该模拟一个存储库吗?并且该数据还应该包括期望值?

最佳答案

您在此示例中未使用存储库,因此无需模拟任何内容。您可以做的是为不同的可能输入创建多个单元测试:

[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
}

等等,您可以添加其他单元测试,您只需更改每个可能输入的 arrangeassert 阶段。

关于c# - 具有多个输入的单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9240158/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com