Thursday, October 25, 2012

C#: Testing for CLS Compliance

I was working on refactoring some C# code in an assembly when some of the error messages about CLS Compliance didn't seem to make sense.  It was then I discovered that the assembly had not been marked as CLS Compliant.  I plan on writing a second post on some of the reasons for CLS Compliance and also some tips on interpreting compiler warning messages.  But in this post I just want to show a simple unit test that will verify that an assembly has been marked as compliant.

First to visually check if an assembly is compliant, look for this attribute declaration in the assembly.cs source code file:

[assembly: CLSCompliant(true)]

The unit test to check for this is quite simple and just loads the assembly's meta-data.  I am using NUnit but this code can be used with any testing framework.

Here's the test fixture class, with some comments following:

    [TestFixture]
    [CLSCompliant(false)]
    public class AssemblyTestFixture
    {
        Assembly thisAssembly;
        object[] attributes;

        [SetUp]
        public void Setup()
        {
            thisAssembly = Assembly.GetExecutingAssembly();
        }

        [Test]
        public void IsCLSCompliant()
        {
            attributes = this.thisAssembly.GetCustomAttributes(typeof(CLSCompliantAttribute), false);
            Assert.AreEqual(attributes.Length, 1);
            CLSCompliantAttribute csl = (CLSCompliantAttribute)attributes[0];
            Assert.IsTrue(csl.IsCompliant);
        }
    }


Some notes on this code:

1. I mark test fixtures as not CLS Compliant because this is not production code and I often do strange things in Unit Tests. The compiler warnings are disabled this way.

2. Make sure this code is in the assembly you want to test. GetExecutingAssembly always refer to the assembly running the code.

3. If you want to test some other assembly, load the metadata using one of the other Assembly class methods such as Load, LoadFile or LoadFrom.