Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Sample code in framework's AssemblyInfo.cs:

[assembly: System.Runtime.CompilerServices.InternalsVisibleTo
                          ("Test.Company.Department.Core")]

Is this a bad practice?

like image 830
Ian Avatar asked Sep 28 '11 08:09

Ian


People also ask

What makes code difficult for unit testing?

Tightly coupled code is extremely hard to unit test (and probably shouldn't be unit tested - it should be re-factored first), because by definition unit tests can only test a specific unit of something. All calls to databases or other components of the system should be avoided from Unit Tests because they violate this.

Should unit tests cover all cases?

Therefore, automated unit tests should make up the bulk of your tests. Unit tests should validate all of the details, the corner cases and boundary conditions, etc.

Should unit tests only test one thing?

This guideline is much more aggressive and recommended if you work in a test driven manner rather than write the tests after the code has been written. The main goal here is better code coverage or test coverage.


3 Answers

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.

like image 151
Daniel Hilgarth Avatar answered Oct 16 '22 11:10

Daniel Hilgarth


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.

like image 30
Jon Skeet Avatar answered Oct 16 '22 13:10

Jon Skeet


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.

like image 3
Rickard Avatar answered Oct 16 '22 12:10

Rickard