Is there a nice way to make it so that functions are public when I am testing with NUnit, but private otherwise?
Not having to generate a lot of extraneous code would also be nice.
------------------------Edit------------------------
It seems the solutions fall under 3 types:
- don't do what I'm attempti开发者_如何学Cng to do.
- use compiler directives.
- try a clever solution (like using InternalsVisibleTo).
Might there be a way to do this programmatically? i.e. just create a new temporary app that makes all protected/private/internal
functions public
, plug that into NUnit, run the tests there, and then go back to using the private functions for the release version?
Instead of private
<->public
you can make them internal
<->public
using InternalsVisibleTo
.
InternalsVisibleTo
is an assembly attribute that you can use in the assembly you want to make visible to your unit test assembly. You will have to sign your unit test assembly, because the InternalsVisibleTo
attribute relies on the public key of the calling assembly.
You might not need to if you have good coverage on your public methods which call the private methods but that seems to be another debate into it self.
This is a good link about TDD and different ways to do it: How to Test Private and Protected methods in .NET
There's always internal
as others have pointed out, but since that's distinct from both private
and public
(and hence could affect other code in the same assembly), why not use compiler directives:
#define DEBUG
//...
#if DEBUG
public int PublicMethod(int x, int y)
{
return privateMethod(x, y);
}
#endif
private int MethodToTest() {...}
#if DEBUG
public int MethodTested()
{
return MethodToTest();
}
#endif
Test MethodTested()
Try this:
#if DEBUG
public type MethodName(parameters)
#else
private type MethodName(parameters)
#endif
{
// method body
}
Shortly, try this:
#if DEBUG
public
#else
private
#endif
int myMethod(params)
{
// do something.
}
usa as myMethod();
精彩评论