Robert
Robert

Reputation: 4406

In Nunit, Compare two lists of objects so that they contain the same types

I am writing an EFException converter and I am building a Rulset for it. I want to verify that the builder returns a list of the rules:

 [Test]
    public void Build_CreateListOfEntityRules()
    {
        //arrange
        var expected = new List<IEntityRule>
                            {
                                new AutomaticDataLossEntityRule(),
                                new CommitFailedEntityRule(),
                                new DbEntityValidationEntityRule(),
                                new DbUnexpectedValidationEntityRule(),
                                new DbUpdateConcurrencyEntityRule(),
                                new DbUpdateEntityRule(),
                                new EntityCommandCompliationEntityRule(),
                                new EntityCommandExecutionEntityRule(),
                                new EntityErrorEntityRule(),
                                new EntitySqlEntityRule(),
                                new InvalidOperation(),
                                new MigrationEntityRule(),
                                new MigrationsPendingEntityRule(),
                                new ModelValidationEntityRule(),
                                new ObjectNotFound(),
                                new PropertyConstraintEntityRule(),
                                new UnintentionalCodeFirstEntityRule(),
                                new UpdateEntityRule()
                            };

        //act
        var actual = sut.Build();

        //assert
        CollectionAssert.AreEquivalent(expected, actual);

    }

Collection.AreEquivilent, Collection.AreEqual, and Collection.Contains all fail; however, when I manually look at the output of the lists they are the same.

Why doesn't NUnit recognize this?

Upvotes: 0

Views: 318

Answers (1)

Michal Hosala
Michal Hosala

Reputation: 5705

If the test fail and you wouldn't expect it to, then I guess you are not implementing Equals method for some of your classes properly (possibly none of them), because that is the method which ultimately gets called when asserting collections of objects.

If method is not implemented in any of IEntityRule implementations then Equals method of class object is called instead which returns false when compared objects are not the same instance.

To sum it up - solution is to implement public bool Equals(AutomaticDataLossEntityRule other) for AutomaticDataLossEntityRule class and similarly for the rest of the classes.

Upvotes: 2

Related Questions