How to Isolate (detour) constructor of class with Microsoft Fakes Shim?

Dresel picture Dresel · Jul 24, 2012 · Viewed 7.9k times · Source

Is there a possibility to isolate / replace an constructor of a class with Microsoft Fakes?

In found an example for Mole (antecessor of Fakes): http://thecurlybrace.blogspot.co.at/2011/11/how-do-i-detour-mole-type-constructor.html

I tried constructs like this

ShimStreamReader.Constructor = @this => ShimStreamReader.ConstructorString(@this, "Test");

but it says the get accessor is missing. To clarify it would be nice to replace something like

new StreamReader("filename")

with static input like this

new StreamReader(new MemoryStream(Encoding.Default.GetBytes("33\r\n1\r\n16\r\n5\r\n7")))

so that i do not have to mock Read, ReadLine, etc.

Answer

Oleg Sych picture Oleg Sych · Oct 13, 2012
using (ShimsContext.Create())
{
    ShimStreamReader.ConstructorString = 
        delegate(StreamReader @this, string @string)
        {
            var shim = new ShimStreamReader(@this);
            shim.Read = () => 42;
        };

    var target = new StreamReader("MeaningOfLife.txt");
    Assert.AreEqual(42, target.Read());
}