testing an internal class
Asked Answered
M

6

5

how to write unit tests to internal classes ???

Motherhood answered 3/3, 2009 at 12:3 Comment(1)
For recent .NET versions, how to use InternalsVisibleTo attribute.Hypethral
K
14

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.

Kappa answered 3/3, 2009 at 12:10 Comment(0)
I
5

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

Isotope answered 3/3, 2009 at 12:19 Comment(2)
you say you would not recommend this, but how you would you solve something like this? #15441435Coquetry
@Thomas: exactly as Esko states in his answer. Either you test the internal APIs indirectly through your public interface, or you promote your internal APIs to public and test them directly.Isotope
H
2

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.

Hydrostatic answered 3/3, 2009 at 12:10 Comment(0)
P
2

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 ?

Platitude answered 3/3, 2009 at 12:15 Comment(0)
T
1

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.

Thirtythree answered 3/3, 2009 at 12:15 Comment(0)
I
0

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

Ilyse answered 30/6, 2011 at 0:47 Comment(1)
Linked page is no longer availableContrive

© 2022 - 2024 — McMap. All rights reserved.