C# – Comparing two enum *types* for equivalence

cenumsunit testing

In my application, I have two equivalent enums. One lives in the DAL, the other in the service contract layer. They have the same name (but are in different namespaces), and should have the same members and values.

I'd like to write a unit test that enforces this. So far, I've got the following:

public static class EnumAssert
{
    public static void AreEquivalent(Type x, Type y)
    {
        // Enum.GetNames and Enum.GetValues return arrays sorted by value.
        string[] xNames = Enum.GetNames(x);
        string[] yNames = Enum.GetNames(y);

        Assert.AreEqual(xNames.Length, yNames.Length);
        for (int i = 0; i < xNames.Length; i++)
        {
            Assert.AreEqual(xNames[i], yNames[i]);
        }

        // TODO: How to validate that the values match?
    }
}

This works fine for comparing the names, but how do I check that the values match as well?

(I'm using NUnit 2.4.6, but I figure this applies to any unit test framework)

Best Answer

Enum.GetValues:

var xValues = Enum.GetValues(x);
var yValues = Enum.GetValues(y);

for (int i = 0; i < xValues.Length; i++)
{
    Assert.AreEqual((int)xValues.GetValue(i), (int)yValues.GetValue(i));
}