在 shim 中调用原始方法 class

Calling original method in shim class

我想针对某些错误的网络行为测试存储库。我使用 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 会在运行时修改程序集。只要上下文处于活动状态,shimmed 方法的所有调用都会重定向到 shim class 上的静态方法。对于要正常执行的代码部分,您需要显式地跳出 shim 上下文。