gpt4 book ai didi

moq - 对 Mock.Setup 的后续调用会产生相同的对象实例

转载 作者:行者123 更新时间:2023-12-02 06:21:41 24 4
gpt4 key购买 nike

我正在设置一个模拟,如下所示。它被传递到目标的构造函数中。目标有一个 Decrypt 方法,该方法在目标的生命周期内被调用两次。每次调用 Decrypt 方法时,它都会处理在安装程序中“更新”的证书。但是,当第二次调用 Decrypt 对象时,我在尝试解密时得到了一个 ObjectDispose 方法。如果我用调用 GetCertificate() 的 ICertificateHelperAdapter 的 Fake 实现替换此 Mock,则对 Decrypt 的第二次调用可以正常工作。

我推断,当我使用 Mock 时,它不会在后续调用 GetCertificate 时返回该对象的新实例。这是设计使然吗?

    private Mock<ICertificateHelperAdapter> GetCertificateHelperAdapter()
{
Mock<ICertificateHelperAdapter> certificateHelper = new Mock<ICertificateHelperAdapter>();

certificateHelper.Setup(
ch => ch.GetCertificate(CertStoreName.My, StoreLocation.LocalMachine, It.IsAny<string>())).Returns(this.GetCertificate()).Verifiable();
return certificateHelper;
}

private X509Certificate2 GetCertificate()
{
return new X509Certificate2(Environment.CurrentDirectory + "\\" + "azureconfig.pfx", "dingos");
}

最佳答案

Returns<T> 的不同重载行为不同:

带有 T Returns<T>(T value) 的那个您使用的始终返回相同的实例。

但是有一个惰性版本,它使用 Func<T> 。它们看起来像 T Returns<T>(Func<T> value)当调用设置方法时,它们将在每次参数函数时进行评估。

样本来自Moq site :

// lazy evaluating return value
mock.Setup(foo => foo.GetCount()).Returns(() => count);

将您的设置更改为:

certificateHelper.Setup(ch => 
ch.GetCertificate(CertStoreName.My, StoreLocation.LocalMachine, It.IsAny<string>()))
.Returns(() => this.GetCertificate()).Verifiable(); //note the lambda in Returns

它会调用你的 GetCertificate()两次。

关于moq - 对 Mock.Setup 的后续调用会产生相同的对象实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9425449/

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