gpt4 book ai didi

c# - Microsoft Fakes 是否支持 shim 上的抽象方法?

转载 作者:太空狗 更新时间:2023-10-29 23:24:08 26 4
gpt4 key购买 nike

我的类(class)设置如下:

public abstract FooClass {
public FooClass() {
// init stuff;
}

public void RandomMethod() {
// do stuff;
}

public abstract WhatIWantToShim();
}

我想做的是像这样在 ShimFooClass 上设置 WhatIWantToShim:

ShimFooClass.AllInstances.WhatIWantToShim = () => Boo();

我可以很好地设置 RandomMethod,

ShimFooClass.AllInstances.RandomMethod = () => CalculatePi();

但是,生成的 ShimFooClass 似乎没有在 ShimFooClass 的 AllInstances 属性上创建 WhatIWantToShim 属性。

我看过http://msdn.microsoft.com/en-us/library/hh549176.aspx#bkmk_shim_basics但我在那里看不到任何关于抽象方法的信息。我看到唯一不支持的引用是终结器。任何人都知道这里发生了什么,如果支持这种情况?

最佳答案

啊……真可惜

Interfaces and abstract methods. Stubs provide implementations of interfaces and abstract methods that can be used in testing. Shims can’t instrument interfaces and abstract methods, because they don’t have method bodies.

http://msdn.microsoft.com/en-us/library/hh549175(v=vs.110).aspx

更新:虽然可以做的是对 shim 进行 stub 。

using (ShimsContext.Create())
{
bool wasAbstractMethodCalled = false;
var targetStub = new StubFooClass()
{
WhatIWantToShim01 = () => wasAbstractMethodCalled = true
};
var targetShim = new ShimFooClass(targetStub);
targetShim.AllInstances.RandomMethod = () => CalculatePi();
FooClass target = targetShim.Instance;
target.WhatIWantToShim();
Assert.IsTrue(wasAbstractMethodCalled, "The WhatIWantToShim method was not called.");
}

由于 shim 无法处理绕过 WhatIWantToShim 方法而 stub 可以,因此只需创建 stub 类的新实例并为抽象方法设置绕行处理程序。 (注意:在我的实际代码中生成 Fakes 时,WhatIWantToShim 末尾标记的 01 是自动为我添加的)。

然后只需将实例化的 stub 传递给 shim 类的构造函数,并根据需要进行 shim 处理。

关于c# - Microsoft Fakes 是否支持 shim 上的抽象方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15822826/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com