Resource File Testing

April 18, 2014

Admittedly this does sound like a strange one. How or why would you both to test a resource file? The only reason I could think of was this: what if someone adds a resource, and forgets to localise it?

Without a test such as this, the first way you’d know this is when you ran the program in a localised culture and spotted the default culture appearing. This is something that could potentially go unnoticed for a long time. Consider British and American English, or Spanish and Latin-American Spanish.

To set-up the test, create three resource files:

res1

Create two resources in the base resource file (.resx):

res2

And then in each localised file, create one of these; so, in Resource.en-GB.resx create testphraseone (test phrase one english), and in the Spanish: testphrasetwo (prueba frase dos).

We also need to expose the resource manager:


    public class GetRes
    {
        public static ResourceManager GetResMgr()
        {            
            ResourceManager resMgr = new ResourceManager("resourcetest.Properties.Resource", typeof(resourcetest.Properties.Resource).Assembly);
            return resMgr;
        }

The Test

Now that we have the ResourceManager, we can simply call the GetResourceSet function. The third parameter determines whether to try the parent if the resource doesn’t exist, so setting this to false will force it to get the resource from the file in question.

The test could look like this:


        [TestMethod]
        public void TestMethod1()
        {
            ResourceManager resMgr = resourcetest.GetRes.GetResMgr();
            
            var baseList = resMgr.GetResourceSet(CultureInfo.InvariantCulture, true, true).Cast();            
            var spanishList = resMgr.GetResourceSet(new CultureInfo("es-ES"), true, false).Cast();
            var britishList = resMgr.GetResourceSet(new CultureInfo("en-GB"), true, false).Cast();
            
            var missing = baseList.Where(m => !spanishList.Any(s => string.Compare(s.Key.ToString(), m.Key.ToString()) == 0));
            Assert.AreEqual(0, missing.Count());

            missing = baseList.Where(m => !britishList.Any(s => string.Compare(s.Key.ToString(), m.Key.ToString()) == 0));
            Assert.AreEqual(0, missing.Count());
        }

This should then fail every time it encounters a resource in the base list that is not localised. If you needed to see the reverse, you could simply reverse the statement.

Conclusion

If you work in multiple languages, this can prove to be a very useful test. It also means that you can safely decide to delay the translation without being concerned that you’ll miss anything.



Profile picture

A blog about one man's journey through code… and some pictures of the Peak District
Twitter

© Paul Michaels 2024