Recently i had to make a solution still targeting version 4.0 of the .Net framework to compile and run on a machine with .Net 4.5 . This was the first step of migrating that solution to 4.5.
First i have created a test environment (VS2010 + .Net 4.0) where i made sure that the everythig is fine (solution compiles and all tests pass) before attempting to install .net 4.5. After installing 4.5 almost all projects compiled, except the unit test projects using moles. It seems moles generated source for .Net 4.5 types, however the unit test projects were set to target version 4.0. (One example of this is the SqlCredential class)
After seraching on the web i found the suggested workaround for this, namely to exclude the problematic types using the .moles file, however this did not work for me.
I needed more information from moles so i tried to turn on logging to verbose level, however setting that from the .moles file did not gave any usable results. When checking the build output i found out that the moles msbuild task generates an options file and runs moles.exe using that file as settings file. This settings file can be found in obj\moles\moles.args. I modified this file by adding /d for enabling diagnostic mode and /v:Noisy for detailed logging. Then i ran moles.exe and passed the modified @moles.args as parameter. From the logs it was clear that moles is trying to load the 4.0 reference assembly from the reference assemblies directory, however the assembly with the same version is loaded from the GAC (which is in place updated to 4.5). Checking the code with ILSpy, it turned out that moles loads assemblies in two separate ways depending on the ReflectionOnly attribute. If this is set to true, the correct reference assembly gets loaded into the reflection only load context, otherwise the GAC 4.5 assembly gets loaded. After modifying all the moles files to use ReflectionOnly=”true”, all the moles assemblies got generated successfully (using 4.0 code) and all the tests passed (except one, that found an incompatible change in .Net 4.5).
As it turned out setting the ReflectionOnly property to true can solve moles compilation errors in projects targeting .Net 4.0 on a machine having 4.5 installed.