user499054
user499054

Reputation:

Is there an access modifier that limits to a solution?

In my .NET solution, I have two projects: one main project and a project for running tests against the main project. In my project, I have several methods that I'd like to keep "private", but would also like to run tests for. Is there an access method that could limit these functions to just inside of my solution?

Upvotes: 5

Views: 2602

Answers (4)

lenkan
lenkan

Reputation: 4405

You are looking for the InternalsVisibleTo attribute.

This attributes lets you specify other assemblies that should have access to types and methods that are internal to your assembly. So, in your main project AssemblyInfo.cs file (or any other source file), you can specify that your test project is a 'friend assembly' and should have access to the internals of your main project:

[assembly:InternalsVisibleTo("MainProject.Tests")]

On a side note, as pointed out by Alexei, if your MainProject is signed with a strong name key, any 'friend' assembly must also be signed. This is explained here

Although, as mentioned in another comment. Best practice is to test your assembly by using its public API.

Upvotes: 15

Alexei Levenkov
Alexei Levenkov

Reputation: 100527

No, there is no way to limit access to "just solution".

The reason is solution is simply group of projects. One project can be in any number of solutions. So even if you "limit" access to projects included in one solution you/someone else can create another solution that somehow will need to magically get access to methods.

Additionally built assembly does not include any information on what solution it was part of - so there is no information at run time to check access.


To you particular problem - InternalsVisibleTo (as shown in other answers) will give access to internal methods to projects you allow (requires strongly signed assemblies) or refactor your code to avoid need for testing private methods.

Upvotes: 2

Tim Bee
Tim Bee

Reputation: 2230

You should seriously think back about the architecture of your solution. This is a smell that often shows that your class does too much things at once.

A simple fix is to extract this responsibility (those private methods) to another class where they then become public and are testable out of the box...

Upvotes: 2

Jakub Lortz
Jakub Lortz

Reputation: 14896

You can use InternalsVisibleTo attribute to make internal types and methods visible to selected assemblies.

However, you should try to design your API so that it can be tested using only the public interface.

Upvotes: 2

Related Questions