How to make unit test private functions from a separate project in VB.NET?

When I develop code, I often want to unit test some of the building blocks of a class, even if they are usually private. If my unit tests are inside the project, I can use Friend to do this and still keep the functions private for normal use. But I would rather move my NUnit tests to my own separate projects. How to achieve the effect I'm looking for?

+5
source share
3 answers

You cannot (easily) test private methods from another project, but quite often internal methods ( Friendin VB) are tested from a test project using InternalsVisibleToAttribute. This makes members Friendavailable for another assembly.

Apparently this was new in VB 9, although it was available in C # 2 ... it's not entirely clear why, but this Bart de Smet blog post gives a quick example.

Please note that if your production assembly is signed, your test assembly must also be signed, and you will need to specify the public key in the arguments InternalsVisibleToAttribute. See this answer for more details .

+11
source

You can use Reflection to call private methods. There are many samples for this.

+3

Google: http://www.codeproject.com/KB/cs/testnonpublicmembers.aspx

Basics: (this is pasted from the site of the project code site linked above)

        public static object RunStaticMethod(System.Type t, string strMethod,
  object []  objParams) 
    {
        BindingFlags eFlags = 
         BindingFlags.Static | BindingFlags.Public | 
         BindingFlags.NonPublic;
        return RunMethod(t, strMethod, 
         null, aobjParams, eFlags);
    } //end of method

    public static object RunInstanceMethod(System.Type t, string strMethod, 
     object objInstance, object [] aobjParams) 
    {
        BindingFlags eFlags = BindingFlags.Instance | BindingFlags.Public | 
         BindingFlags.NonPublic;
        return RunMethod(t, strMethod, 
         objInstance, aobjParams, eFlags);
    } //end of method

    private static object RunMethod(System.Type t, string 
     strMethod, object objInstance, object [] aobjParams, BindingFlags eFlags) 
    {
        MethodInfo m;
        try 
        {
            m = t.GetMethod(strMethod, eFlags);
            if (m == null)
            {
                 throw new ArgumentException("There is no method '" + 
                  strMethod + "' for type '" + t.ToString() + "'.");
            }

            object objRet = m.Invoke(objInstance, aobjParams);
            return objRet;
        }
        catch
        {
            throw;
        }
    } //end of method
+1
source

All Articles