I have a class which contains several structs:
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 a unit test I make 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 the Assert.AreEqual always throws AssertFailedException. The objects are identical, I've verified this using debugger. Please share any ideas. Thanks.
The call Assert.AreEqual(expected, expected) should not fail. 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 will the call to Assert.AreEqual always fail, cause your type NavigationMenu is a class and therefore a reference type, even if you set the properties of the instances to the same values.
Assert.AreEqual performs an equality check if the two variables point to the same reference (aka. ReferenceEqual) and not if the two references contain the same (property) values.
You could override the Equals method of your NavigationMenu class to provide a custom implementation if two instances of your class are equal.
Because you are (probably) comparing two different instances of an 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 a comparison there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With