We pay for user submitted tutorials and articles that we publish. Anyone can send in a contributionLearn More
I am currently working on a project with a pluggable application (load plugins at runtime and execute them) that loads assemblies at runtime, using the Assembly.LoadFile() method. I wanted to test it using NUnit (feel free to read our 3 Ways to Run NUnit from Visual Studio post). Although, the code was functioning very well it always failed during the NUnit tests, always! It took me several days to understand what went wrong and I want to share with you my findings.
First, lets take a look at this very simple plugin code:
The pluggable application defines the interface for its plugins: ITinyPlugin. In another assembly, the IncPlugin class implements ITinyPlugin. Here is the test code:
There is a false test where 4 should be different from 5 and then using the plugin, 4 is incremented and the result is being compared to 5. You would expect the test to pass, but like me, you are wrong! Before explaining the flow, we need to know how to load an assembly (plugin) at runtime and execute its code:
Usually, the plugins are located inside a ‘”Plugins” directory in the execution path. The code above, get the plugin directory path and read all of the assemblies located in it. It then, loads the first assembly, take the class that implements ITinyPlugin and use its Increment method. Everything looks fine, and believe me it also works fine in a standalone application (i.e not through NUnit), so why on earth does this test fails??
Debugging the code, I found out that executionPath variable was different from what I expected and different from its value when this code runs outside NUnit. Due to that fact, the Assembly.LoadFile() method failed because its input which is the assembly full name was wrong. After some more investigation, I realized (using the Modules window - Ctrl + D + M during runtime) that all of my assemblies are loaded from a temporary location:
“C:\Documents and Settings\shahar\Local Settings\Temp\nunit20\ShadowCopyCache\3880_633459266024531250\Tests\
Well, it turns out that NUnit, by default, uses a shallow copy option to run its tests. All of the assemblies needed for the execution of the test are copied to a temporary folder so that the original assemblies won’t be locked. Using this approach, the user can run his tests and work with Visual Studio at the same time. The problem here is that our Plugins folder wasn’t copied and hence wasn’t found during the test.
If you want to disable the shadow copy option (version 2.4.6), just go to NUnit GUI, Tools->Test Loader->Advanced and check the “Disable shadow copy” checkbox. Close NUnit and re-run your tests - Everything is fine now, the tests are green!!!
Hope you found this post helpful, enjoy…
Tags :assemblyBugLoadFileNUnitpluggablepluginruntimeshallow copy
Copyright © 2012 Dev102.com
Breeze : Designed by Amit Raz and Nitzan Kupererd