Friday, August 19, 2005

Using C#/.net Reflection to call Private and Protected methods

Today I learned that it is possible to call private and protected methods by using reflection.
This is a great technique for Unit Testing such critters for proper behavior when 'code that shuold never be reached' gets reached.

Example:


internal string GetAString(int stringId)
{
foreach(DataRow dr in _theDataSet.Tables["mySTringTable"].Rows)
{
if((int)dr["strID"] == stringId)
return((string)dr["theStringValue"]);
}

//Impossible or very difficult to create a test situation
// where this code would ever get executed. The methods
// that DO have access to this method ALWAYS pass a valid stringId.
throw new NotFoundException("String not found!");
}


Check out this link:

http://www.codeproject.com/csharp/TestNonPublicMembers.asp

Or google:

"reflection unit test private method"

No comments:

C# Sucks!

JK!! Seriously, though, somewhere around C#-3 we should have inculcated ourselves with the question: "Does 'CAN' == 'SHOULD...