1

I didn't create the framework but I need to write test for it. The scenario...

  • It uses WeakReference to hold an object, there's a base method that I call to assign object to it (BaseClass.Register(weakObject))
  • I can retrieve that object through a method (BaseClass.GetObject())
  • Testing it... I had to register my mock (BaseClass.Register(mockWeak.Object)) first

When executing a method that relies on the registered object, my test sometimes fails because it has been garbage collected before i performed test to it.

Can I do something to prevent GC from collecting my WeakReference object?

NOTE: No changes should be done in the framework (BaseClass), only in my test class

Filburt
  • 17,626
  • 12
  • 64
  • 115
Marc Vitalis
  • 2,129
  • 4
  • 24
  • 36

1 Answers1

1

Sorry, I found an answer to this... During testing you should make use of...

GC.KeepAlive(weakObject)

Full reference here.

http://defragdev.com/blog/?p=129

Marc Vitalis
  • 2,129
  • 4
  • 24
  • 36