【问题标题】:How to use Microsoft Fakes framework to shim an instance method?如何使用 Microsoft Fakes 框架填充实例方法?
【发布时间】:2013-12-12 22:23:53
【问题描述】:

我在 VS2012 中使用 Microsoft Fakes 框架。

我使用以下代码填充我的类型的 instance 方法。

    using (ShimsContext.Create())
    {
        ShimDateTime.NowGet = () => { return new DateTime(1949, 10, 1); };
        DateTime now = DateTime.Now;  // shim works for the static property DateTime.Now.

        Class1 dependency = new Class1();


        using (ShimsContext.Create())
        {
            ShimClass1 shim1 = new ShimClass1();
            StubClass1 stub1 = new StubClass1();
            shim1.method1 = () => { return "shim method1"; };
            shim1.IMethod1 = () => { return "shim IMethod1"; };

            String s1 = dependency.method1();// shim doesn't work for the instance method.
            String s2 = dependency.IMethod1();// shim doesn't work for the instance method.
        }

class1 如下所示:

public class Class1 : Interface1
{
    public String method1()
    {
        return "real method1";
    }

    //Interface 1 member
    public string IMethod1()
    {
        return "real IMethod1";
    }
}

我希望 s1 和 s2 是匀场输出,但它仍然是实际输出。

为什么?

【问题讨论】:

    标签: unit-testing mocking microsoft-fakes


    【解决方案1】:

    如果 'method1' 是静态的,那么您的 shim 就会起作用。但是,使用当前代码,您并没有真正消除“method1”。您需要将该实例与 shim 实例相关联

    Class1 依赖 = new ShimClass1() { Method1 = () => { return "Shim.Method1"; } };

    或将所有实例方法与您的委托关联

    ShimClass1.AllInstances.Method1 = (q)=> { return "Shim.Method1"; };

    我也认为不需要将 ShimsContext.Create() 完成两次

    如果你想使用存根重定向 IMethod1,你应该使用 StubInterface1 来代替

    Class1 依赖 = new StubInterface1() { Method1 = () { return ""; } };

    msdn 上提供了这些变体以供参考

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-19
      • 1970-01-01
      • 2018-11-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-02
      • 1970-01-01
      相关资源
      最近更新 更多