UnitTesting – not public methods

Sometime there is necessity to test internal or private methods. Normally it’s not possible as unit tests should generaly test public methods.
Still if you really need to test internal method see example below.
Imagine we have a class:

    public class Person
    {
        public Person(string firstName, string lastName, int age)
        {
            FirstName = firstName;
            LastName = lastName;
            Age = age;
        }


        public string FirstName { get; private set; }
        public string LastName { get; private set; }
        public int Age { get; private set; }


        internal int CalculateBirthYear() // the internal method to be tested
        {
            return DateTime.Now.Year - Age;
        }
    }

To test this internal method, you should add a line: “[assembly:InternalsVisibleTo(“Common.UnitTests”)]” to AssemblyInfo.cs file in your project.
Then internals are visible to your test project (project you put in AssemblyInfo).

Sometime there is necessity to test private methods. Imagine that method from the previous example is now private.
To access it you should use PrivateObject class in your test project. See example below:

        [TestMethod]
        public void CalculateBirthYearTest()
        {
            var person = new Person("John", "Smith", 20); // the object to test
            PrivateObject o = new PrivateObject(person);
            var year = (int)o.Invoke("CalculateBirthYear"); // the method name to test

            Assert.IsTrue(year == 1996);
        }

The other ways to access private methods is private accessor, but it is deprecated since VisualStudio 2012. One more way is reflection, but it is easier to use PrivateObject.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s