I\'m building a class library that will have some public & private methods. I want to be able to unit test the private methods (mostly while developing, but also it coul
If you want to unit test a private method, something may be wrong. Unit tests are (generally speaking) meant to test the interface of a class, meaning its public (and protected) methods. You can of course "hack" a solution to this (even if just by making the methods public), but you may also want to consider:
CC -Dprivate=public
"CC" is the command line compiler on the system I use. -Dfoo=bar
does the equivalent of #define foo bar
. So, this compilation option effectively changes all private stuff to public.
You could also declare it as public or internal (with InternalsVisibleToAttribute) while building in debug-Mode:
/// <summary>
/// This Method is private.
/// </summary>
#if DEBUG
public
#else
private
#endif
static string MyPrivateMethod()
{
return "false";
}
It bloats the code, but it will be private
in a release build.
On CodeProject, there is an article that briefly discusses pros and cons of testing private methods. It then provides some reflection code to access private methods (similar to the code Marcus provides above.) The only issue I've found with the sample is that the code doesn't take into account overloaded methods.
You can find the article here:
http://www.codeproject.com/KB/cs/testnonpublicmembers.aspx
Well you can unit test private method in two ways
you can create instance of PrivateObject
class the syntax is as follows
PrivateObject obj= new PrivateObject(PrivateClass);
//now with this obj you can call the private method of PrivateCalss.
obj.PrivateMethod("Parameters");
You can use reflection.
PrivateClass obj = new PrivateClass(); // Class containing private obj
Type t = typeof(PrivateClass);
var x = t.InvokeMember("PrivateFunc",
BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Public |
BindingFlags.Instance, null, obj, new object[] { 5 });
I use PrivateObject class. But as mentioned previously better to avoid testing private methods.
Class target = new Class();
PrivateObject obj = new PrivateObject(target);
var retVal = obj.Invoke("PrivateMethod");
Assert.AreEqual(retVal);