Blog Home  Home RSS 2.0 Atom 1.0 CDF  
IdentityCrisis - Unit Test Const keys against Resouce Files
Code is a commodity. Platform awareness ... Priceless
 
 Wednesday, February 01, 2006

I have a resource file (.resx) with some keys and values.  I created a Resource class to wrap access to the System.Resources.ResourceManager.  In the Resource class I created a class filled with just constants so I would have a nice intellisence experience while developing.  Although this helps eliminate errors when trying to key into the resource file they don’t go away, because I either make mistakes while typing or keep changing my mind and forgetting to change the key text in the three or more places it must change.  So I wrote a nice unit test that tests all constants and verifies I am not using a message value more than once.  I instantly found a couple mistakes.  Now I need a code gen to reverse the .resx file to the Resource.Message class.  (Message might be a bad name. hmm…)  Back to work.

 Sample Resource example:

public Resource {
    public class Messages {
        public const string RES_Validate_UserNameRequired = "RES_Validate_UserNameRequired";
        public const string RES_Validate_UserNameFormat = "RES_Validate_UserNameFormat";
        public const string RES_Validate_UserNameExists = "RES_Validate_UserNameExists";
    }

}

 

Unit test:

[Test]
public void MessageResourceTests() {
    string message;
    string key;
    Hashtable messageTable = new Hashtable(CaseInsensitiveHashCodeProvider.Default, CaseInsensitiveComparer.Default);

    FieldInfo[] fields = typeof(Resource.Messages).GetFields();
   
    foreach(FieldInfo field in fields){
        if (field.IsLiteral) {
            key = field.GetValue(null).ToString();
            message = Resource.MessageResourceManager.FormatMessage(key);
            Assert.IsNotEmpty(message);
            Assert.IsFalse(messageTable.ContainsValue(message), "Resource message duplicate: [{0}]{1}",key,message);
            messageTable[key] = message;
        }
    }
}

2/1/2006 5:33:53 AM (GMT Standard Time, UTC+00:00)  #       | 
Copyright © 2010 Joseph E Shook. All rights reserved.
DasBlog 'Portal' theme by Johnny Hughes.
Pick a theme: