使用Microsoft Fakes与工厂实例方法

时间:2012-10-09 12:32:59

标签: c# testing factory shim microsoft-fakes

我有一个看起来像这样的课程:

public class MyClass
{
    int myNum;

    private MyClass() {}

    public static MyClass CreateInstance()
    {
        MyClass a = new MyClass();
        a.myNum=5;
        return a;
    }

    public bool IsBigger(MyClass b)
    {
        return this.myNum > b.myNum;
    }

}

然后,我想制作一个垫片并希望使用IsBigger方法,但默认情况下它返回false。在这种情况下如何调用基本方法?

测试结果如下:

[TestMethod]
Public void test()
{
 ShimMyClass firstShim = new ShimMyClass();
 firstShim.myNumGet = () => { return 6; }

 ShimMyClass secondShim = new ShimMyClass();
 secondShim.myNumGet = () => { return 7; }

 Assert.IsTrue(secondShim.Instance.IsBiggerThan(firstShim.Instance);
}

1 个答案:

答案 0 :(得分:0)

让MyNum成为一个财产:

public class MyClass
{
    public int MyNum { get; private set; }

    private MyClass() {}

    public static MyClass CreateInstance()
    {
        MyClass a = new MyClass();
        a.MyNum=5;
        return a;
    }

    public bool IsBigger(MyClass b)
    {
        return this.MyNum > b.MyNum;
    }

}

在使用ShimMyClass之前创建Shim Context:

using (ShimsContext.Create())
{ 
    ShimMyClass firstShim = new ShimMyClass();
     firstShim.MyNumGet = () => { return 6; }

     ShimMyClass secondShim = new ShimMyClass();
     secondShim.MyNumGet = () => { return 7; }

     Assert.IsTrue(secondShim.IsBiggerThan(firstShim);
}

Microsoft Fakes on MSDN