How to mock/isolate internal classes in VS 2012 wi

2020-07-06 05:09发布

问题:

So, the issue is that I have a bunch of internal classes in my assembly that are used by the class I want to test. Since accessors have been removed from VS2012, I'm fine with using [InternalsVisibleTo] and that works great... except when I try to shimify my internal classes, they are not visible to the Fakes framework. I should also note that the particular class I am dealing with is a static class with static methods, and I don't really want to refactor everything to use interfaces (and using stubs) because of resistance in the organization to that level of refactoring.

Is there a way to make these internal members usable by the shims context in Visual Studio 2012 without resorting to interfacing (literally) everything?

回答1:

The following page describes how to make internal types visible to the generated fakes assembly. http://msdn.microsoft.com/en-us/library/hh708916.aspx#bkmk_internal_types

Which says:

The Fakes code generator will generate shim types and stub types for types that are visible to the generated Fakes assembly. To make internal types of a shimmed assembly visible to Fakes and your test assembly, add InternalsVisibleToAttribute attributes to the shimmed assembly code that gives visibility to the generated Fakes assembly and to the test assembly.

So you need an InternalsVisibleToAttribute that grants your test assembly access to the internal types of the target assembly. In other words:

[assembly: InternalsVisibleTo("TargetAssembly.Fakes")]
[assembly: InternalsVisibleTo("TestAssembly")]