title: How do I mock Func<T> factory dependency to return different objects using AutoMock?
body: <p>I'm trying to write a test for a class that has a constructor dependency on <code>Func&lt;T&gt;</code>. In order to complete successfully the function under test needs to create a number of separate objects of type <code>T</code>.</p>
  <p>When running in production, AutoFac generates a new <code>T</code> every time <code>factory()</code> is called, however when writing a test using AutoMock it returns the same object when it is called again.</p>
  <p>Test case below showing the difference in behaviour when using AutoFac and AutoMock. I'd expect both of these to pass, but the AutoMock one fails.</p>
  <pre><code>public class TestClass
  {
      private readonly Func&lt;TestDep&gt; factory;
  
      public TestClass(Func&lt;TestDep&gt; factory)
      {
          this.factory = factory;
      }
  
      public TestDep Get()
      {
          return factory();
      }
  }
  
  public class TestDep
  {}
  
  [TestMethod()]
  public void TestIt()
  {
      using var autoMock = AutoMock.GetStrict();
  
      var testClass = autoMock.Create&lt;TestClass&gt;();
  
      var obj1 = testClass.Get();
      var obj2 = testClass.Get();
  
      Assert.AreNotEqual(obj1, obj2);
  }
  
  [TestMethod()]
  public void TestIt2()
  {
      var builder = new ContainerBuilder();
  
      builder.RegisterSource(new AnyConcreteTypeNotAlreadyRegisteredSource());
              
      var container = builder.Build();
  
      var testClass = container.Resolve&lt;TestClass&gt;();
              
      var obj1 = testClass.Get();
      var obj2 = testClass.Get();
  
      Assert.AreNotEqual(obj1, obj2);
  }
  </code></pre>