检查对象时,NUnit Has.Member失败

时间:2012-06-05 09:19:56

标签: c# unit-testing nunit ienumerable

我有以下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的测试,但他们都通过了。

我做错了什么?

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:6)

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

  

对于引用,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)));