Added a TypeRegistrar to CommandAppTester

exposed as a public property.
For convenience, and to keep the similarity to the real CommandApp
it is also available in the ctor of CommandAppTester.
This commit is contained in:
Nils Andresen
2021-06-21 15:52:12 +02:00
committed by Patrik Svensson
parent b92827ce3d
commit 6b5b31957c
4 changed files with 91 additions and 3 deletions

View File

@ -8,6 +8,7 @@ namespace Spectre.Console.Testing
{
public Dictionary<Type, List<Type>> Registrations { get; }
public Dictionary<Type, List<object>> Instances { get; }
public Func<Dictionary<Type, List<Type>>, Dictionary<Type, List<object>>, ITypeResolver> TypeResolverFactory { get; set; }
public FakeTypeRegistrar()
{
@ -50,7 +51,7 @@ namespace Spectre.Console.Testing
public ITypeResolver Build()
{
return null;
return TypeResolverFactory?.Invoke(Registrations, Instances);
}
}
}

View File

@ -0,0 +1,41 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Spectre.Console.Cli;
namespace Spectre.Console.Testing
{
public sealed class FakeTypeResolver : ITypeResolver
{
private readonly Dictionary<Type, List<Type>> _registrations;
private readonly Dictionary<Type, List<object>> _instances;
public FakeTypeResolver(
Dictionary<Type, List<Type>> registrations,
Dictionary<Type, List<object>> instances)
{
_registrations = registrations ?? throw new ArgumentNullException(nameof(registrations));
_instances = instances ?? throw new ArgumentNullException(nameof(instances));
}
public static Func<Dictionary<Type, List<Type>>, Dictionary<Type, List<object>>, ITypeResolver> Factory =>
(r, i) => new FakeTypeResolver(r, i);
public object Resolve(Type type)
{
if (_instances.TryGetValue(type, out var instances))
{
return instances.FirstOrDefault();
}
if (_registrations.TryGetValue(type, out var registrations))
{
return registrations.Count == 0
? null
: Activator.CreateInstance(type);
}
return null;
}
}
}