In my application, I have two equivalent enum
s. 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)
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));
}
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 ) );
}
}
}
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