Como alguém se refere a um stub que possui um parâmetro genérico usando o Microsoft Fakes?
-
12-12-2019 - |
Pergunta
Estou usando o Microsoft Fakes em alguns testes de unidade nos quais estou trabalhando.Minha interface fica assim:
interface ISecuredItem<TChildType> where TChildType : class, ISecuredItem<TChildType>
{
SecurityDescriptor Descriptor { get; }
IEnumerable<TChildType> Children { get; }
}
Uma implementação típica disso é semelhante a:
class RegistryKey : ISecuredItem<RegistryKey>
{
public SecurityDescriptor Descriptor { get; private set; }
public IEnumerable<RegistryKey> Children { get; }
}
Gostaria de usar essa interface com o Microsoft Fakes e fazer com que ela gerasse um esboço para mim.O problema é que a forma que Fakes usa é StubInterfaceNameHere<>
, então no exemplo acima você acaba tentando fazer algo como StubISecuredItem<StubISecuredItem<StubISecuredItem<StubISecuredItem....
Isso é possível?Se sim, como faço para usar Fakes dessa forma?
Solução
Depois de algumas experiências, encontrei uma solução funcional, embora não seja a mais elegante.
Este é o seu código normal:
public interface ISecuredItem<TChildType>
where TChildType : ISecuredItem<TChildType>
{
SecurityDescriptor Descriptor { get; }
IEnumerable<TChildType> Children { get; }
}
No seu projeto de teste você cria uma interface StubImplemtation
public interface StubImplemtation : ISecuredItem<StubImplemtation> { }
Então, no seu teste de unidade, você pode fazer o seguinte:
var securedItemStub = new StubISecuredItem<StubImplemtation>
{
ChildrenGet = () => new List<StubImplemtation>(),
DescriptorGet = () => new SecurityDescriptor()
};
var children = securedItemStub.ChildrenGet();
var descriptor = securedItemStub.DescriptorGet();
Você pode pular todo StubImplementation
E use RegistryKey
se isso não for problema.