简体   繁体   中英

C# - How to mock this.GetType().Assembly

In the code I'm working on, I'm forced to test one method where there is a call like this:

this.GetType().Assembly.GetTypes().Where(x => ...);

I would like to mock this call so that when the call is made an assembly of my choice is retrieved from this.GetType().Assembly .
In the assembly there will be fake types that I will use for my assertions

The approach I'm trying (still without success) is using shims, as described here .

Is there a way to achieve my goal?

Finally, note that I know this is not the right approach to do unit testing. Usually the classes I test are made using dependency I can easily mock. This is an exception as this is an implementation of Cunsomer-Driven Contracts that is solution-wide and I'm not allowed to change it.

If you cannot change the code under test, you could use a framework like TypeMock or JustMock . Those frameworks use profiler hooks and can, therefore, redirect every function call made, even calls to third-party libraries.

This would allow you to redirect the call to the getter of this.GetType().Assembly and return a preset list of assemblies.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM