Unit test private methods?

There has been a lot of discussion about whether we should unit test private methods, which I find it very interesting to read on my spare time). However, in this post I am not going to add more arguments on this subject (I will leave it to your own discretion πŸ™‚ ). Here, I am going to show an example on using PrivateObject class which can be handy if you need to test a private method or property or field. The class exists in Microsoft Visual Studio Unit Test and you can read on MSDN for more information. In short, this class gives access to private methods (and properties). Let’s say I have an Account class which I want to test:

public class Account
        public decimal InterestRate { get; private set; }        
        private decimal _balance;
        private int _accountId;

        public Account(int accountId)
            _accountId = accountId;

        private void InitAccount()
            //Populate Account details, i.e. current balance

        public decimal GetBalanceWithInterest()
            return _balance + GetInterest();

        private decimal GetInterest()
            return _balance*InterestRate;

If I want to test the GetInterest method, which is private, I could do the following:

        public void GetInterest_ReturnsExpectedInterest()
            decimal balance = 1000;
            decimal interestRate = (decimal) 0.05;
            decimal expectedInterest = 50;

            var acc = new Account(1000);
            var privateObject = new PrivateObject(acc);

            privateObject.SetField("_balance", balance);
            privateObject.SetProperty("InterestRate", interestRate);

            var interest = privateObject.Invoke("GetInterest");

            Assert.AreEqual(interest, expectedInterest);

The example above invokes the private method without passing any arguments. To pass arguments, you can use an array of object as follows:

privateObject.Invoke("APrivateMethod", new object[] { param1, param2});

That’s it, quite simple isn’t πŸ™‚

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s

%d bloggers like this: