microsoft-fakestypemock

Can MS Fakes create future mock objects?


In TypeMock you can create a future mock object, for example:

public class ClassToTest
{   
    public ClassToTest()
    {
        var o = new Foo();
    }
}

[Test]
public void Test()
{
    var fakeFoo = Isolate.Fake.Instance<Foo>();

    Isolate.Swap.NextInstance<Foo>().With(fakeFoo);
}

Does MS Fakes have the same functionality as the above?


Solution

  • I found a great example from this SO question which demonstrates how to fake future instances of objects. Here's an example from that question:

    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            ClassLibrary1.Child myChild = new ClassLibrary1.Child();
    
            using (ShimsContext.Create())
            {
                ClassLibrary1.Fakes.ShimChild.AllInstances.addressGet = (instance) => "foo";
                ClassLibrary1.Fakes.ShimParent.AllInstances.NameGet = (instance) => "bar";
    
                Assert.AreEqual("foo", myChild.address);
                Assert.AreEqual("bar", myChild.Name);
            }
    
        }
    }
    

    This looks like it will do the trick for me.