Question

how to write unit tests to internal classes ???

Was it helpful?

Solution

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.

If the internal class cannot be adequately tested through the top-level class' interface, then it's usually best to move the internal class out and test it directly as a new top-level class. Wanting to test internal classes is a code smell that the internal class might be significant enough to be a top-level class.

OTHER TIPS

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

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.

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 ?

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.

See the detailed explanations from http://msdn.microsoft.com/en-us/library/bb385974.aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top