gpt4 book ai didi

c# - 在 shim 类中调用原始方法

转载 作者:太空宇宙 更新时间:2023-11-03 19:59:46 25 4
gpt4 key购买 nike

我想针对某些错误的网络行为测试存储库。我使用 MS Fakes 伪造了类(class),它看起来像这样:

ShimInputRepository
.AllInstances
.UpdateEngagementStringNullableOfInt64NullableOfInt32String = (xInst, xEngId, xTrimUri, xTargetVers, xComments) =>
{


if (xEngId != initializer.SeededEngagementsWithoutEmp[3].EngagementId)
{
return xInst.UpdateEngagement(xEngId, xTrimUri, xTargetVers, xComments); //Unfortunately, calls recursively same method (not the original one)
}
else
{
throw new Exception
(
"An error occurred while executing the command definition. See the inner exception for details.",
new Exception
(
"A transport-level error has occurred when receiving results from the server. (provider: Session Provider, error: 19 - Physical connection is not usable)"
)
);

}
};

我不知道如何使用该代码调用原始方法(目前它递归调用相同的方法)。

如何调用原始方法?

更新:我真正想要实现的是在对此方法(“if() ...”语句)的特定调用上抛出异常,否则将调用转发给原始实例。

最佳答案

Fakes 框架为这种情况提供了支持。您可以使用:

ShimInputRepository
.AllInstances
.UpdateEngagementStringNullableOfInt64NullableOfInt32String = (xInst, xEngId, xTrimUri, xTargetVers, xComments) =>
{


if (xEngId != initializer.SeededEngagementsWithoutEmp[3].EngagementId)
{
return ShimsContext.ExecuteWithoutShims(() => xInst.UpdateEngagement(xEngId, xTrimUri, xTargetVers, xComments));
}
else
{
throw new Exception
(
"An error occurred while executing the command definition. See the inner exception for details.",
new Exception
(
"A transport-level error has occurred when receiving results from the server. (provider: Session Provider, error: 19 - Physical connection is not usable)"
)
);

}
};

ShimsContext.ExecuteWithoutShims 方法将在当前 shim 上下文之外执行 Func< T >(例如,没有导致无限循环的 shim 重定向)。

无限循环的原因是创建 ShimContext 会在运行时修改程序集。只要上下文处于事件状态,填充方法的所有调用都会重定向到填充类上的静态方法。对于要正常执行的代码部分,您需要显式地跳出 shim 上下文。

关于c# - 在 shim 类中调用原始方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29705304/

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