0

I want to test private methods.

Unit testing private methods in C#

I tried the fifth solution. ie : using reflection

using System;
using System.Reflection;

namespace tobeDEleted
{
    static class classA {
        private static void method1() { Console.WriteLine(1); }
    }

    class classB
    {
        private void method2() { Console.WriteLine(2); }
        private static void method3() { Console.WriteLine(3); }
    }

    class Program
    {
        static void Main(string[] args)
        {

            var objb = new classB();
            MethodInfo methodInfo1 = typeof(classA).GetMethod ("method1", BindingFlags.NonPublic | BindingFlags.Instance);
            MethodInfo methodInfo2 = typeof(classB).GetMethod("method2", BindingFlags.NonPublic | BindingFlags.Instance);
            MethodInfo methodInfo3 = typeof(classB).GetMethod("method3", BindingFlags.NonPublic | BindingFlags.Instance);


            object[] parameters = { };
            methodInfo2.Invoke(obj, parameters);
            methodInfo3.Invoke(obj, parameters);


        }
    }
}

as expected methodInfo3 throw a exception:

System.NullReferenceException: 'Object reference not set to an instance of an object.'

Is there a similar method as GetMethod for static methods.

I don't know too, how to test an static class.

  • 1
    `BindingFlags.Instance` is asking for an instance method, which a `static` method is not. Nor can you pass an object instance to a static method, obviously. Also, consider using `internal` rather than `private` if the method is worth testing (possibly combined with the `InternalsVisibleTo` attribute); reflection is very brittle. Even giving the class its own dedicated `internal` method to run the tests would be better, if you really don't want to expose anything. Testing with reflection creates a hidden dependency as much as anything else, and fixing it if it break is no fun. – Jeroen Mostert Apr 16 '21 at 09:14
  • I cannot but compelety agree Jeroen. If you feel something needs to be testet, make it `internal` at least. For getting a legacy-codebase *into* unit-tests, you won´t come around reflection, but you should refactor as soon as possible to avoid the nasty hidden dependencies and turn them into more explicit ones. – MakePeaceGreatAgain Apr 16 '21 at 09:23
  • Having said this as soon as your test successfully runs, you can and should perform some refactoring. – MakePeaceGreatAgain Apr 16 '21 at 09:26

0 Answers0