【问题标题】:How to check list orders (further properties) with NUnit?如何使用 NUnit 检查列表订单(更多属性)?
【发布时间】:2016-06-07 10:24:21
【问题描述】:

我希望 NUnit 测试一个列表顺序,基于两个属性而不是一个。

片段代码(工作):

var list = new List<Tuple<string, string>>
{
    new Tuple<string, string>("aaaa", "bbbb"),
    new Tuple<string, string>("bbbb", "aaaa"),
    new Tuple<string, string>("aaaa", "cccc"),
    new Tuple<string, string>("cccc", "bbbb")
};
var ordered = list.OrderBy(p => p.Item1).ThenBy(p => p.Item2);
Assert.That(ordered, Is.Ordered.By("Item1"));

片段代码(我想要的 - 不工作):

var list = new List<Tuple<string, string>>
{
    new Tuple<string, string>("aaaa", "bbbb"),
    new Tuple<string, string>("bbbb", "aaaa"),
    new Tuple<string, string>("aaaa", "cccc"),
    new Tuple<string, string>("cccc", "bbbb")
};
var ordered = list.OrderBy(p => p.Item1).ThenBy(p => p.Item2);
Assert.That(ordered, Is.Ordered.By("Item1").ThenBy("Item2"));
// Below syntax works but does not return expected result
// Assert.That(ordered, Is.Ordered.By("Item1").By("Item2"));

【问题讨论】:

  • 什么不起作用?
  • .ThenBy("Item2") in "Assert.That(ordered, Is.Ordered.By("Item1").ThenBy("Item2"));"
  • 看来你必须编写自己的扩展来实现这一点。

标签: c# .net unit-testing nunit nunit-3.0


【解决方案1】:

显然,您知道 NUnit 中没有 ThenBy 语法元素,但希望 By 多次应用。这两个功能都不可用,并且 CollectionOrderedConstraint 仅支持单个属性名称。在 NUnit 中实现这两种方法都不是很困难,因此您应该考虑提交问题以请求该功能。

目前,这是不可能的。您应该考虑以正确的顺序创建预期的元组列表并使用测试这两个列表是否相等的解决方法。

【讨论】:

【解决方案2】:

作为另一种选择,您可以查看应该的框架并执行以下操作

    [TestMethod]
    public void GivenAnUnorderListWhenCustomOrderExecutedThenItemsOrderbyItemOneThenByItemTwo()
    {
        var expectedOrder = new List<Tuple<string, string>>
        {
                    new Tuple<string, string>("aaaa", "bbbb"),
                    new Tuple<string, string>("aaaa", "cccc"),
                    new Tuple<string, string>("bbbb", "aaaa"),
                    new Tuple<string, string>("cccc", "bbbb")
        };

        var list = new List<Tuple<string, string>>
        {
                    new Tuple<string, string>("aaaa", "bbbb"),
                    new Tuple<string, string>("bbbb", "aaaa"),
                    new Tuple<string, string>("aaaa", "cccc"),
                    new Tuple<string, string>("cccc", "bbbb")
        };

        var orderedList = list.OrderBy(p => p.Item1).ThenBy(p => p.Item2);
        orderedList.ShouldBe(expectedOrder);
    }

【讨论】:

  • 在我的真实案例中,它是一个 SQL 查询。为了更简单,我将其转换为元组。所以使用 SQL 查询的 expectedOrder 更难测试。
猜你喜欢
  • 1970-01-01
  • 2018-01-31
  • 2019-07-08
  • 2011-06-26
  • 1970-01-01
  • 2022-11-09
  • 2011-02-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多