0

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

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);
}
4

1 回答 1

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 上下文:

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

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

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

MSDN 上的微软假货

于 2012-10-09T12:35:27.493 回答