2

我有以下 NUnit 测试:

[Test]
    public void GetComplexRulesTestContents()
    {
        var _rule = new RuleViewModel(null, "third rule", "description");
        var result = _complexRulesService.GetComplexRules();

        Assert.That(result, Has.Member(_rule));

    }

从 _complexRulesService.GetComplexRules() 调用的代码是:

public IEnumerable<IRuleViewModel> GetComplexRules()
    {

        IEnumerable<RuleViewModel> _rules;
        _rules = new List<RuleViewModel>
                     {
                         new RuleViewModel(null, "first default rule", "description"),
                         new RuleViewModel(null, "second default rule", "description"),
                         new RuleViewModel(null, "third rule", "description")
                     };
        return _rules;
    }

我得到的错误信息是:

PL.Web.MVC.Rules.Tests.ComplexRulesServiceTests.GetComplexRulesTestContents:
Expected: collection containing <PL.Web.MVC.Models.Rules.RuleViewModel>
But was:  < <PL.Web.MVC.Models.Rules.RuleViewModel>, PL.Web.MVC.Models.Rules.RuleViewModel>, <PL.Web.MVC.Models.Rules.RuleViewModel> >

我已经尝试了来自http://www.nunit.org/index.php?p=collectionConstraints&r=2.5.5的测试,它们都通过了。

我做错了什么?

提前感谢您的帮助!

4

1 回答 1

6

Has.Member使用对象相等性来验证集合是否包含项目:

对于引用,Has.Member 使用对象相等来查找集合中的成员。

这意味着,将使用默认相等比较来比较您的类是否相等,默认相等比较(除非您覆盖它)是对象引用相等。这些都是 4 个不同的实例。

您可以使用一些 LINQ 执行简单的谓词匹配来解决您的问题:

var expectedItem = results.FirstOrDefault(vm => vm.Property1 == null
    && vm.Name == "third rule" && vm.Description == "description");
Assert.That(expectedItem, Is.Not.Null);

或者,为了使其更简洁,您可以将自定义相等比较方法添加到您的测试类中,并将其与谓词匹配一起使用以更流畅:

private bool RulesMatch(RuleViewModel actual, RuleViewModel expected)
{
    return actual.Property1 == expected.Property1
        && actual.Name == expected.Name
        && actual.Description == expected.Description;
}

Assert.That(results, Has.Some.Matches<RuleViewModel>(v => RulesMatch(v, _rule)));
于 2012-06-05T10:09:50.930 回答