Skip to content

Instantly share code, notes, and snippets.

@MathieuAuclair
Last active March 19, 2019 16:08
Show Gist options
  • Save MathieuAuclair/aa4eafe9de3cecdfd05719a9a28b0669 to your computer and use it in GitHub Desktop.
Save MathieuAuclair/aa4eafe9de3cecdfd05719a9a28b0669 to your computer and use it in GitHub Desktop.
Testing private members using reflexion

Creating test for private members!

Note that this is not a regular use case. Reflexion should be avoided, and your code structure should always be adapted for tests. Perhaps if you don't have the choice, private properties can still be tested!

let's see an example here with a selfish encapsulated class

public class SelfishClass
{
    private string[] Goodies {get; set;}

    SelfishClass()
    {
         Console.WriteLine("Nobody can access my goodies! HAHAHAHA");
         Goodies = GetSomeGoodies();
    }

    private void GetSomeGoodies()
    {
        Console.WriteLine("thoses goodies are mine!");
        return {"Food", "Swag", "CoolSticker"};
    }
}

Your tests!

using Microsoft.VisualStudio.TestTools.UnitTesting;

[TestClass]
class ReflexionTestSample 
{
     [TestMethod]
     public void TestPrivateMembersInitialization()
     {
         var property = typeof(SelfishClass)
                  .GetProperty("Goodies", BindingFlags.Instance | BindingFlags.NonPublic);

         if (property == null)
         {
             throw new DeprecatedException("the Goodies property could not be found, did it changed name?");
         }
         
         var selfishClass = new SelfishClass();
         
         var value = (string[])property.GetValue(selfishClass);
         
         Assert.IsFalse(value.isEmpty());
         Console.WriteLine("I have your goodies! HAHAHA");
     }
     
     [TestMethod]
     public void TestCreateNewGoodiesFromPrivateFunction()
     {
        var selfishClass = new SelfishClass();
     
        var method = typeof(SelfishClass)
                  .GetMethod("GetSomeGoodies", BindingFlags.Instance | BindingFlags.NonPublic);
                  
         if (method == null)
         {
             throw new DeprecatedException("the GetGoodies method could not be found, did it changed name?");
         }
         
         var goodies = (string[])method
                  .Invoke(selfishClass, new object[]{/* parameters here */});
         
         Assert.IsFalse(goodies.IsEmpty());
     }
}

A custom error to explain failed tests!

public class DeprecatedException : System.Exception
{
    public DeprecatedException(string message) : base(message)
    {
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment