【问题标题】:How can I Unit Test This When There's No Public Constructor?如果没有公共构造函数,我该如何进行单元测试?
【发布时间】:2021-04-21 22:39:42
【问题描述】:

我为自己编写了一个方便的小扩展方法来与目录服务一起使用 - 只需将 NT 域与 UserId 放在一起,然后在传递它们之前将它们连接起来:

public static IEnumerable<string> NtUserIds(this ResultPropertyCollection coll)
{        
    var domains = coll[ntDomain].Cast<string>();
    var ids = coll[ntUserID].Cast<string>();
    return domains.Zip(ids, (domain, id) => $"{domain}\\{id}");
}

我想对其进行单元测试,但我很烦恼 - 我无法创建 ResultPropertyCollection,因为它没有 public 构造函数。

我打算将它最小化,但索引器返回一个 ResultPropertyValueCollection - 没有 public 构造函数。

【问题讨论】:

  • 对不起,我不明白。您想要(需要)模拟的依赖项是什么?
  • 我需要创建一个单元测试创​​建一个 ResultPropertyCollection 并调用我的扩展方法来测试它的功能 - 但我无法创建一个 ResultPropertyCollection 因为没有公共构造函数。

标签: c# unit-testing moq


【解决方案1】:

ResultPropertyCollection 确实有一个 internal parameterless ctor

通过反射,您可以创建这样的实例:

var ctor = typeof(ResultPropertyCollection).GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic).First();
var instance = (ResultPropertyCollection)ctor.Invoke(null);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-29
    • 2023-03-16
    • 2020-09-16
    • 1970-01-01
    • 1970-01-01
    • 2013-07-16
    • 1970-01-01
    相关资源
    最近更新 更多