How to test c# private and protect method using NUnit

1,781 views
Skip to first unread message

jens...@gmail.com

unread,
Dec 31, 2009, 4:54:32 AM12/31/09
to NUnit-Discuss
Hi All,

I have a question is that I can't test the Private or Protect method
which is belongs to a Class.

Currently, I am using the Reflector to invoke private method, it looks
like can't cover all methods and lines.

The greatly appreciate if you could provide me the solutions.
Thank you.
Jenson

Markus Ewald

unread,
Dec 31, 2009, 6:19:03 AM12/31/09
to nunit-...@googlegroups.com
You can only invoke private methods through Reflection. One workaround
is to declare said methods internal and use the 'InternalsVisibleTo'
attribute to make them visible to your unit test assembly. But I
wouldn't recommend that because:

Generally, you want to write your Unit Tests so they test a class'
public interface - or, more accurately, the behavior promised by the
interface. The idea is that you can change the implementation (= private
methods) and the tests will still pass as long as the behavior exposed
by the class stays the same. Otherwise, unit test might become an
obstruction to change instead of an enabler.

If you can't stimulate a specific code path through public methods, it
must be a dead code path that can be eliminated.
If it becomes to difficult to find out how to stimulate a specific code
path, try writing more and smaller classes.

:)

> Jenson
>
>
-Markus-

jens...@gmail.com

unread,
Dec 31, 2009, 10:42:00 AM12/31/09
to NUnit-Discuss
Hi Markus,

Thank you for resolve my doubts.

Regards

On Dec 31, 7:19 pm, Markus Ewald <cy...@nuclex.org> wrote:
> On 12/31/2009 10:54 AM, jenso...@gmail.com wrote:> Hi All,

Gerard Meszaros

unread,
Jan 3, 2010, 4:33:02 AM1/3/10
to nunit-...@googlegroups.com
There is another way to access non-public attributes and methods of a class and that is by creating a test-specific subclass which exposes the non-pubic properties. This is a reasonable approach to use when you don't want the normal clients of a class to be able to see these attributes but the test requires them (usually to set up the initial state or to verify the outcome.)  See http://xunitpatterns.com/Test-Specific%20Subclass.html for examples.

Gerard

Markus Ewald wrote:
-Markus-

--

You received this message because you are subscribed to the Google Groups "NUnit-Discuss" group.
To post to this group, send email to nunit-...@googlegroups.com.
To unsubscribe from this group, send email to nunit-discus...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/nunit-discuss?hl=en.



  

-- 
Gerard Meszaros
1-403-827-2967 or m...@gerardmeszaros.com

Author of the Jolt Productivity Award winning book "xUnit Test Patterns - Refactoring Test Code".
Learn more at http://xunitpatterns.com/index.html

Reply all
Reply to author
Forward
0 new messages