Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two enum *types* for equivalence?

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)

like image 495
Roger Lipscombe Avatar asked Sep 11 '09 10:09

Roger Lipscombe


2 Answers

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));
}
like image 145
Darin Dimitrov Avatar answered Sep 18 '22 11:09

Darin Dimitrov


I would flip the way you check around. It is easier to get a name from a value instead of a value from a name. Iterate over the values and check the names at the same time.

public static class EnumAssert
{
    public static void AreEquivalent(Type x, Type y)
    {
        // Enum.GetNames and Enum.GetValues return arrays sorted by value.
        var xValues = Enum.GetValues(x);
        var yValues = Enum.GetValues(y);

        Assert.AreEqual(xValues.Length, yValues.Length);
        for (int i = 0; i < xValues.Length; i++)
        {
            var xValue = xValues.GetValue( i );
            var yValue = yValues.GetValue( i );
            Assert.AreEqual(xValue, yValue);
            Assert.AreEqual( Enum.GetName( x, xValue ), Enum.GetName( y, yValue ) );
        }
    }
}
like image 20
Mike Two Avatar answered Sep 22 '22 11:09

Mike Two