dexter
dexter

Reputation: 7203

How to ensure that a method can only be called from a specific dll

I need to prepare my database for unit testing and hence in the set up method I want to get rid of the data.

However, I don't want to be anybody else but the unit test dll to be able to call into my DeleteAllData() method in my Data Access Layer. What can be done?

Upvotes: 1

Views: 204

Answers (5)

Jenish Rabadiya
Jenish Rabadiya

Reputation: 6766

I have one more approach to achieve thing mentioned in the question.

If you are using VSTS unit test.

Make the method as private in class so that other classes and assemblies can not access that.

Now to invoke that private method from Unit test use PrivateObject

Here is Microsoft documentation of the PrivateObject :- link

How to use Private Object :- link

Upvotes: 0

MvdD
MvdD

Reputation: 23436

While others already suggested how to restrict code making calls to your method, they do not create a security boundary and can be spoofed (unless you sign both assemblies and verify the evidence).

Having a method in your business logic called DeleteAllData sounds pretty scary to me. If this method is only used from a unit test, I would probably move it to the unit test assembly. If that is not possible, I would at least put the code in a compiler directive to only compile in debug mode.

Upvotes: 3

Sam Holder
Sam Holder

Reputation: 32936

you could probably use a combination of Assembly.GetCallingAssembly() and interrogation of the call stack in your DeleteAllData() method to ensure that your method is only being called by the method you expect.

You might need to prevent the jitter inlining your method calls to ensure that the calling assembly method and call stack are preserved when they get to your DeleteAllData() method.

The call stack might be enough, but the calling assembly might also be needed.

I've not tried this but think it should work in theory.

Upvotes: 1

Chris Pratt
Chris Pratt

Reputation: 239290

Mark it with the internal keyword. From the MSDN docs:

The internal keyword is an access modifier for types and type members. Internal types or members are accessible only within files in the same assembly

Upvotes: 0

Patrick Hofman
Patrick Hofman

Reputation: 156978

You can sign both your assemblies, and then use the InternalsVisibleTo attribute to make the unit test assembly the only one able to see the internals. You need to make all methods, properties and classes internal that you only want to expose to the unit test project.

MSDN on the InternalsVisibleToAttribute:

Specifies that types that are ordinarily visible only within the current assembly are visible to a specified assembly.

Upvotes: 1

Related Questions