Monday, December 24, 2012

Read Private Type using Visual Studio Unit Testing in C#

small things can make a different

I want to read my class  private values to verify the unit testing using MS unit test.

Here is the sample code

Created the sample class named NumberChecker, it contains two private property and public method.
The method going to check, the passed number is greater than zero or not. based on that it's going to pass a different message back the client.


namespace PrivateTypeDemo
{
    public class NumberChecker
    {
        private const string Validmessage = "The Number is Greater than Zero";
        private const string DefaultMessage = "The Number is Zero or Less than Zero";
        public string ValidateNumber(int number)
        {
            return number > 0 ? Validmessage : DefaultMessage;
        }
    }
}
Here is the console application which consumes the library

namespace PrivateTypeDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            var numcheck = new NumberChecker();
            Console.WriteLine("Please Enter your Number");
            var  number = Convert.ToInt32(Console.ReadLine());
            var result = numcheck.ValidateNumber(number);
            Console.WriteLine(result);
 
 
        }
    }
}

Unit Test for the NumberCheck class
 [TestClass]
    public class NumberCheckerTest
    {
        [TestMethod]
        public void ValidateNumberTest()
        {
            var target = new NumberChecker();
            const int number = 15;
            var privateType = new PrivateType(target.GetType());
            var expected = privateType.GetStaticFieldOrProperty("Validmessage");
            string actual = target.ValidateNumber(number);
            Assert.AreEqual(expected, actual);
        }
        [TestMethod]
        public void ValidateNumber2Test()
        {
            var target = new NumberChecker();
            const int number = -5;
            var privateType = new PrivateType(target.GetType());
            var expected = privateType.GetStaticFieldOrProperty("DefaultMessage");
            string actual = target.ValidateNumber(number);
            Assert.AreEqual(expected, actual);
        }
        [TestMethod]
        public void NumberCheckerConstructorTest()
        {
            var target = new NumberChecker();
            Assert.IsNotNull(target);
        }
    }
The below lines does the magic of accessing the private type of the classes.This class is shipped part of the 
Microsoft.VisualStudio.TestTools.UnitTesting Assembly  which support this functionality in unit Testing

var privateType = new PrivateType(target.GetType());
var expected = privateType.GetStaticFieldOrProperty("DefaultMessage");

Here i am reading the value of DefaultMessage through the GetStaticFieldOrProperty Method in the PrivateType class
To Learn More about this,
PrivateType