Comparing two types of enum * for equivalence?

In my application, I have two equivalent enum s. One lives in the DAL, the other at the contract service level. They have the same name (but are in different namespaces) and must have the same elements and values.

I would like to write a unit test that will provide this. So far I have 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 is great for comparing names, but how do I check if the values ​​match?

(I am using NUnit 2.4.6, but I suppose this applies to any unit test framework)

+6
enums c # unit-testing
source share
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)); } 
+13
source share

I would flip as you check. It is easier to get the name from the value instead of the value from the 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 ) ); } } } 
+1
source share

All Articles