views:

357

answers:

5

how to write unit tests to internal classes ???

+11  A: 

You write tests which specify the behaviour of the top-level class' external interface. Whether that class uses internal classes to implement that behaviour or not, is an implementation detail of the class, and the tests don't need to know anything about it.

Esko Luontola
A: 

When using MS Visual Studio for Unit Tests you have to simply create a private Accessor. Internally it works with reflections i think. Just take a look at the generated code.

Alexander
+2  A: 

You don't test it directly. It will be tested through the class where it is defined.

And, if you apply TDD, as this question tags currently implies, what is the test you just write that call for an inner class ? I mean can't it be a standard class, privately owned by the class you're working on ?

philippe
+1  A: 

We have used a helper class which uses reflection to load and call methods on internal classes. It is also possible to change the accessibility at compile time using the DEBUG symbol eg

#if DEBUG
public
#else
internal
#endif
    class MyInternalClass
{
    ...
}

However Esko Luontola's answer is more correct as it is the functionality or business requirements which are most important. It is easy to get too focused on code coverage rather than testing the important risk areas.

bstoney
+1  A: 

Not that I'd recommend it, but you can also use the InternalsVisibleToAttribute.

HTH, Kent

Kent Boogaart