【问题标题】:Unit test for a function in C# using Moq使用 Moq 对 C# 中的函数进行单元测试
【发布时间】:2018-10-03 20:00:25
【问题描述】:

我正在尝试使用 Moq 在 C# 中为以下函数编写单元测试,但我发现在验证和其他 Moq 概念时有点不知所措。

public X509Certificate GetCertificate(string certificateName)
        {
            var settingOverride = this.settings.SecretOverridesSetting.FirstOrDefault(secret => secret.Name.Equals(certificateName, StringComparison.InvariantCultureIgnoreCase));
            if (settingOverride != null)
            {
                X509Certificate targetCertificate;
                var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
                store.Open(OpenFlags.ReadOnly);
                X509Certificate2Collection certColl = store.Certificates.Find(X509FindType.FindByThumbprint, settingOverride.Value, false);
                if (certColl.Count == 0)
                {
                    return null;
                }

                targetCertificate = certColl[0];
                store.Close();
                return targetCertificate;
            }
            else
            {
                return SecretStoreClientHelper.GetCertificate(certificateName);
            }
        }

这是我第一次用任何语言为函数编写单元测试。 有人可以帮助我解决一些单元测试场景,我可以在哪些地方使用 Moq。

【问题讨论】:

  • 第一次在没有 Moq 或任何其他模拟框架的情况下编写测试。纯 c# 代码。

标签: unit-testing moq


【解决方案1】:

您需要以不与任何实现紧密耦合的方式重构此代码。因为您不能使用 MOQ 模拟类的非虚拟方法。

请参阅链接https://github.com/Moq/moq4/wiki/Quickstart,了解有关使用 MOQ 创建测试方法的更多详细信息。

【讨论】:

    猜你喜欢
    • 2021-10-15
    • 2011-12-24
    • 2017-04-12
    • 2012-06-01
    • 2022-10-13
    • 1970-01-01
    • 1970-01-01
    • 2011-01-30
    相关资源
    最近更新 更多