Roy Osherove

View Original

Implementing Unit Test MetaData using XtUnit custom attributes

Regarding my last post on xml comments used inside a unit test Here's how you can implement the same "metadata on a test" equivalent using XtUnit custom attributes (note that you need to inhering from a custom class for this):

 

using NUnit.Framework;
using XtUnit.Framework.Internal;

[TestFixture]
    public class CustomDataAttributes:TestFixtureBase
    {
        [Test]
        [Data("sql","Select * from categories")]
        public void useCustomDataAttributes()
        {
            string actual = DataAttribute.items["sql"];
            string expected = "Select * from categories";
            Assert.AreEqual(expected,actual);
        }
    }

    [AttributeUsage(AttributeTargets.Method)]
    class DataAttribute:ProcessingAttributeBase
    {
        private readonly string data = string.Empty;
        private readonly string name = string.Empty;
        public string Name {get { return name; }}
        public string Data { get { return data; } } 
        public DataAttribute(string name, string data)
        {
            this.data = data;
            this.name = name;
        }


        public static readonly Dictionary<string, string> items =                                         new Dictionary<string, string>();         public static Dictionary<string, string> Items
        {get { return items; }  }

        protected override void OnPreProcess()
        {
            items[name] = data;
        }

        protected override void OnPostProcess()
        {   }
    }