Why Assert.AreEqual (T obj1, Tobj2) fails with identical objects

I have a class that contains several structures:

public class NavigationMenu { public struct NavigationMenuItem { public bool Enabled { get; set; } public int NumberOfPendingOperations { get; set; } } public NavigationMenuItem SubmitExpenses { get; set; } public NavigationMenuItem ManageExpenses { get; set; } public NavigationMenuItem SubmitBudgets { get; set; } public NavigationMenuItem ManageBudgets { get; set; } public NavigationMenuItem AuthorizeExpenses { get; set; } public NavigationMenuItem ApproveExpenses { get; set; } public NavigationMenuItem PayExpenses { get; set; } public NavigationMenuItem BillExpenses { get; set; } public NavigationMenuItem ManageReturnedExpenses { get; set; } public NavigationMenuItem ManageIncompleteExpenses { get; set; } public NavigationMenuItem ManageOrders { get; set; } public NavigationMenuItem ApproveBudgets { get; set; } public NavigationMenuItem AdministrateSystem { get; set; } } 

In unit test, I call a function call and compare the results:

 NavigationMenu expected = new NavigationMenu(); expected.SubmitExpenses = new NavigationMenu.NavigationMenuItem { Enabled = true }; expected.ManageExpenses = new NavigationMenu.NavigationMenuItem { Enabled = true }; NavigationMenu actual = HomeControllerHelper.GetNavigationMenuByUserRole(userRole); Assert.AreEqual(expected, actual); 

But Assert.AreEqual always throws an AssertFailedException. The objects are identical, I checked this with a debugger. Please share your ideas. Thanks.

+8
c # unit-testing nunit
source share
3 answers

Call Assert.AreEqual (expected, expected) should not be interrupted. If you made a mistake in your question, and you meant Assert.AreEqual (expected, actual) , and your HomeControllerHelper.GetNavigationMenuByUserRole returns a new instance of NavigationMenu, then calling Assert.AreEqual always fails, your NavigationMenu type is called - this is the class and, therefore, a reference type, even if you set the properties of instances with the same values.

Assert.AreEqual performs equality checking if two variables point to the same link (aka. ReferenceEqual), and not if two links contain the same (property) value.

You can override the Equals method of your NavigationMenu class to provide a custom implementation if two instances of your class are equal.

+6
source share

Assuming this should be Assert.AreEqual(expected, actual); As stated in the comments above:

You must determine how to compare the NavigationMenuItem objects. Atm is his only test, if it is the same instance, and obviously they are not so assertive, they should fail.

+3
source share

Because you are (possibly) comparing two different instances of the object, but with the same parameters. In order for the objects to be "equal", you need to override the Equals method on the object and implement the comparison there.

+3
source share

All Articles