8

In some of my test helper code, I have a IDbSet(Of T) implementation called FakeDbSet(Of T) that mocks a lot of EF behavior without an actual database. I have the class declared Friend because I want to force all code to interact with it like an IDbSet(Of T). Internally (ie within my Testing assembly), I access a lot of the public members of the class which I want to be able to test.

The problem is, I keep my unit tests in a separate assembly Test.Unit which means they cannot access my internal implementation! I know I can get around this with reflection, but that gets cumbersome and messy very quickly. Is there any better way to set up my project to avoid this problem?

just.another.programmer
  • 8,579
  • 8
  • 51
  • 90

1 Answers1

8

Add this to your AssemblyInfo.cs file:

[assembly:InternalsVisibleTo("YourOtherAssembly")]

This will make your internal assemblies visible to YourOtherAssembly. However, you should really consider if you need to have it internal. When writing tests try focusing on your public parts.

Read more here: http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx

Tomas Jansson
  • 22,767
  • 13
  • 83
  • 137
  • I am new to unit testing in .NET - but isn't there a built in tension here? On the one hand, I am encouraged to make as many things as possible to Friend scope. To reduce visibility. On the other hand, I can then not create any unit tests for those classes, because the test project can not see those Friend classes. I'm confused. – Prof. Falken Jun 26 '19 at 14:06
  • @Prof.Falken the focus of tests should be on the exposed behavior of a module. – Tomas Jansson Jul 02 '19 at 09:26
  • No disagreement there - but it's pretty common I think, to treat a class as a "module" of sorts. *internal* methods however can be used between classes sharing the same project or whatever it is. But since the unit tests typically are in another project in the same assembly, they do no have access to *internal* methods. This feels awkward at best. – Prof. Falken Jul 02 '19 at 17:45
  • 1
    @Prof.Falken, Ah, I got your point. Yes, definitely awkward, and I tend to not use `internal` for that reason. I think a class should keep as much as possible private and only expose what needs to be exposed. If there is a "private" algorithm that needs testing I would actually extract that to its own class and make that algorithm public. – Tomas Jansson Jul 02 '19 at 21:40