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

标签 c# unit-testing mocking

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

考虑以下几点:

我有一个 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/

相关文章:

testing - 我应该使用内存数据库而不是模拟我的存储库吗?

c# - TryGetObjectByKey 未在 .net 4.5 中编译

c# - ASP.NET 4.5 C# Forms 身份验证访问拒绝登录页面

c# - 重新抛出 ex.InnerException 是个坏主意?

c# - ObjectContext 已被 EnsureConnection() 在连续查询中抛出(未使用导航属性且未使用())

python - Pytest:将一个 fixture 传递给另一个

c# - 调用了单元测试 ThrowIfCancellationRequested()

android - AppCompat 21 lollipop 更新使 Robolectric 单元测试失败并出现VerifyError

java - 如何为 Java 8 谓词编写 Mockito 测试

c# - 如何在模拟对象内创建模拟对象?