如何使用 Microsoft Fakes 引用本身具有通用参数的存根?
-
12-12-2019 - |
题
我在我正在进行的一些单元测试中使用 Microsoft Fakes。我的界面如下所示:
interface ISecuredItem<TChildType> where TChildType : class, ISecuredItem<TChildType>
{
SecurityDescriptor Descriptor { get; }
IEnumerable<TChildType> Children { get; }
}
其典型实现如下所示:
class RegistryKey : ISecuredItem<RegistryKey>
{
public SecurityDescriptor Descriptor { get; private set; }
public IEnumerable<RegistryKey> Children { get; }
}
我想将此接口与 Microsoft Fakes 一起使用,并让它为我生成一个存根。问题是,Fakes 使用的形式是 StubInterfaceNameHere<>
, ,所以在上面的例子中你最终会尝试做类似的事情 StubISecuredItem<StubISecuredItem<StubISecuredItem<StubISecuredItem....
这可能吗?如果是这样,我该如何以这种方式使用Fakes?
解决方案
经过一些实验,我找到了一个可行的解决方案,尽管它不是最优雅的。
这是您的常规代码:
public interface ISecuredItem<TChildType>
where TChildType : ISecuredItem<TChildType>
{
SecurityDescriptor Descriptor { get; }
IEnumerable<TChildType> Children { get; }
}
在您的测试项目中,您创建一个 StubImplementation 接口
public interface StubImplemtation : ISecuredItem<StubImplemtation> { }
然后在单元测试中您可以执行以下操作:
var securedItemStub = new StubISecuredItem<StubImplemtation>
{
ChildrenGet = () => new List<StubImplemtation>(),
DescriptorGet = () => new SecurityDescriptor()
};
var children = securedItemStub.ChildrenGet();
var descriptor = securedItemStub.DescriptorGet();
你可以跳过整个 StubImplementation
并使用 RegistryKey
如果没问题的话。
不隶属于 StackOverflow