From dc402220f23e4cd310a8ce70ea76380343f4b7d9 Mon Sep 17 00:00:00 2001 From: Nils Andresen Date: Fri, 10 Nov 2023 23:05:55 +0100 Subject: [PATCH] (#1313) fixed errors in FakeTypeRegistrar and FakeTypeResolver to make the unit tests pass. --- .../FakeTypeRegistrar.cs | 8 ++++ .../FakeTypeResolver.cs | 37 ++++++++++++++++--- 2 files changed, 39 insertions(+), 6 deletions(-) diff --git a/src/Spectre.Console.Testing/FakeTypeRegistrar.cs b/src/Spectre.Console.Testing/FakeTypeRegistrar.cs index 91dec0b..124477a 100644 --- a/src/Spectre.Console.Testing/FakeTypeRegistrar.cs +++ b/src/Spectre.Console.Testing/FakeTypeRegistrar.cs @@ -44,6 +44,10 @@ public sealed class FakeTypeRegistrar : ITypeRegistrar { Instances.Add(service, new List { implementation }); } + else + { + Instances[service].Add(implementation); + } } /// @@ -58,6 +62,10 @@ public sealed class FakeTypeRegistrar : ITypeRegistrar { Instances.Add(service, new List { factory() }); } + else + { + Instances[service].Add(factory()); + } } /// diff --git a/src/Spectre.Console.Testing/FakeTypeResolver.cs b/src/Spectre.Console.Testing/FakeTypeResolver.cs index b89634f..7a313a0 100644 --- a/src/Spectre.Console.Testing/FakeTypeResolver.cs +++ b/src/Spectre.Console.Testing/FakeTypeResolver.cs @@ -1,3 +1,5 @@ +using System.Collections; + namespace Spectre.Console.Testing; /// @@ -29,18 +31,41 @@ public sealed class FakeTypeResolver : ITypeResolver return null; } + if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable<>)) + { + // return all registrations + type = type.GenericTypeArguments[0]; + var allRegistrations = Activator.CreateInstance(typeof(List<>).MakeGenericType(type)); + var castList = allRegistrations as IList; + + if (_instances.TryGetValue(type, out var listInstances)) + { + listInstances.ForEach(i => castList.Add(i)); + } + + if (_registrations.TryGetValue(type, out var listRegistrations)) + { + listRegistrations + .Select(x => Activator.CreateInstance(x)!) + .ToList() + .ForEach(i => castList.Add(i)); + } + + return allRegistrations; + } + if (_instances.TryGetValue(type, out var instances)) { - return instances.FirstOrDefault(); + return instances.LastOrDefault(); } if (_registrations.TryGetValue(type, out var registrations)) - { - // The type might be an interface, but the registration should be a class. - // So call CreateInstance on the first registration rather than the type. + { + // The type might be an interface, but the registration should be a class. + // So call CreateInstance on the first registration rather than the type. return registrations.Count == 0 - ? null - : Activator.CreateInstance(registrations[0]); + ? null + : Activator.CreateInstance(registrations.Last()); } return null;