0

I am trying to write a unit test (NUnit) that will:

  1. Create an instance of some Form.
  2. Hook up the relevant AssemblyLoad event of the AppDomain to build a List of loaded assembly names.
  3. If the same assembly is loaded twice, fail.
  4. Otherwise - pass.

I cannot seem to get the logic for this... The test always passes.

Can this be done ?

lysergic-acid
  • 19,570
  • 21
  • 109
  • 218

2 Answers2

8

It is hard to make your unit test fail. The CLR already makes sure that an assembly only gets loaded once. Pretty important, getting the same assembly loaded more than once produces very hard to diagnose casting errors at runtime.

You'd have to use the horrid Assembly.LoadFile() to trip a fail. Avoid testing things you should never do to begin with.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • This is exactly the way my application actually loads the assemblies ("plugins"). – lysergic-acid Jun 23 '11 at 17:56
  • Well, hopefully the word "horrid" drove the point home. Use LoadFrom(). – Hans Passant Jun 23 '11 at 18:00
  • Why is it horrid? and what is the difference between it and LoadFrom? – lysergic-acid Jun 23 '11 at 18:06
  • Because you can load an assembly more than once if you use LoadFile(). And have to deal with the type identity problem when you do. Objects from the exact same type loaded twice are not assignment compatible. LoadFile should only be used by tools that dump assembly metadata, never any production code. – Hans Passant Jun 23 '11 at 18:15
  • I've checked now, our application uses LoadFrom to load assemblies, however i am still seeing few assemblies loaded twice. Could it be that a type that references this assembly will load it automatically, even if it's already loaded? – lysergic-acid Jun 26 '11 at 10:44
1

Once you load an assembly in the AppDomain, you cannot load it again and there doesn't appear to be an Assembly.Unload method either. Well, technically you can unload the assembly if you unload all of the AppDomains that loaded it.

Kiril
  • 39,672
  • 31
  • 167
  • 226
  • I am having a scenario, where the same assembly gets copied all around to different folders of my app. The same assembly appears under Visual Studio Modules window multiple times (but under different locations). I'd like to verify that using some sort of coded test during my build/CI process. – lysergic-acid Jun 23 '11 at 17:55