title: Visual Studio Unit test ShimsContext messing with Garbage Collector
body: <p>Here is an interesting question: Why does the garbage collection not work for the simple unit test initialization example below? At least for me running VS2013 .NET 4.5 I eventually run out of memory and get a out of memory exception.</p>
  
  <p>The shimmed method is needed, without that the garbage collector works just fine also inside the ShimsContext.</p>
  
  <p>This is boiled down from one of my tests where a large xml file was parsed with several million temporary object creations, eventually leaving me without any memory.</p>
  
  <p>Class under test</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;
  using System.Threading.Tasks;
  
  namespace MemoryTester
  {
      public class Program
      {
          static void Main(string[] args)
          {
          }
  
          static void MethodToFake()
          {
              Console.WriteLine("This is the original method");
          }
      }
  
      public class OutsideClass
      {
          public OutsideClass()
          {
          }
  
          ~OutsideClass()
          {
  
          }
      }
  }
  </code></pre>
  
  <p>Unit test class</p>
  
  <pre><code>using System;
  using Microsoft.VisualStudio.TestTools.UnitTesting;
  using Microsoft.QualityTools.Testing.Fakes;
  
  namespace Tests
  {
      [TestClass]
      public class MemoryTests
      {
          protected IDisposable Context;
  
          [TestInitialize]
          public void InitTest()
          {
              using (ShimsContext.Create())
              {
                  MemoryTester.Fakes.ShimProgram.MethodToFake = () =&gt;
                  {
                      Console.WriteLine("This is the shimmed method");
                  };
  
                  while (true)
                  {
                      //This will never be garbage collected, why?
                      MemoryTester.OutsideClass nc = new MemoryTester.OutsideClass();
                  }
              }
  
              while (true)
              {
                  //Outside of ShimsContext, we will garbage collect just fine
                  MemoryTester.OutsideClass nc = new MemoryTester.OutsideClass();
              }
          }
  
          [TestMethod]
          public void AttributeSerializerMemoryTest()
          {
              Assert.IsTrue(true);
          }
  
          private TestContext testContextInstance;
          public TestContext TestContext
          {
              get
              {
                  return testContextInstance;
              }
              set
              {
                  testContextInstance = value;
              }
          }
      }
  }
  </code></pre>