Is it considered bad practice to use InternalsVisibleTo for Unit Test Code?

No, it is not considered bad practice. There is no other way, if the classes you want to test are internal to your assembly for good reasons. Just not testing them would be a lot worse.


InternalsVisibleTo could be useful if you need to test sub parts of your API which you don't want to expose.

However, testing through the public API is preferable since it makes refactoring internal APIs easier. Use InternalsVisibleTo with care and only when appropriate, e.g. the size of the API is significant.


Personally I think it's fine. I've never gone along with the dogma of "only test public methods". I think it's good to also have black box testing, but white box testing can let you test more scenarios with simpler tests, particularly if your API is reasonably "chunky" and the public methods actually do quite a lot of work.

Likewise, in a well-encapsulated project you may well have several internal types with only internal methods. Now presumably those will have a public impact so you could do all the testing just through the public types - but then you may well need to go through a lot of hoops to actually test something that's really simple to test using InternalsVisibleTo.