Skip to content

Commit

Permalink
Use reflection provider for class constructors
Browse files Browse the repository at this point in the history
  • Loading branch information
nohwnd committed Nov 19, 2024
1 parent a6b6696 commit 333ff83
Showing 1 changed file with 29 additions and 11 deletions.
40 changes: 29 additions & 11 deletions src/Adapter/MSTest.TestAdapter/Execution/TypeCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -260,24 +260,42 @@ private static bool TryGetUnescapedManagedTypeName(TestMethod testMethod, [NotNu
private TestClassInfo CreateClassInfo(Type classType, TestMethod testMethod)
{
IEnumerable<ConstructorInfo> constructors = PlatformServiceProvider.Instance.ReflectionOperations.GetDeclaredConstructors(classType);
ConstructorInfo? constructor = constructors.FirstOrDefault(ctor => ctor.GetParameters().Length == 0 && ctor.IsPublic);
bool isParameterLessConstructor;
(ConstructorInfo? CtorInfo, bool IsParameterless)? selectedConstructor = null;

if (classType.GetConstructor([typeof(TestContext)]) is { } testContextCtor)
foreach (ConstructorInfo ctor in constructors)
{
constructor = testContextCtor;
isParameterLessConstructor = false;
}
else if (classType.GetConstructor([]) is { } parameterLessCtor)
{
constructor = parameterLessCtor;
isParameterLessConstructor = true;
if (!ctor.IsPublic)
{
continue;
}

ParameterInfo[] parameters = ctor.GetParameters();

// There are just 2 ctor shapes that we know, so the code is quite simple,
// but if we add more, add a priority to the search, and shortcircuit this search so we only iterate
// through the collection once, to avoid re-allocating GetParameters multiple times.
if (parameters.Length == 1 && parameters[0].ParameterType == typeof(TestContext))
{
selectedConstructor ??= (ctor, IsParameterless: false);

// This is the preferred constructor, no point in searching for more.
break;
}

if (parameters.Length == 0)
{
selectedConstructor = (ctor, IsParameterless: true);
}
}
else

if (selectedConstructor is null)
{
throw new TypeInspectionException(string.Format(CultureInfo.CurrentCulture, Resource.UTA_NoValidConstructor, testMethod.FullClassName));
}

ConstructorInfo constructor = selectedConstructor.Value.CtorInfo;
bool isParameterLessConstructor = selectedConstructor.Value.IsParameterless;

PropertyInfo? testContextProperty = ResolveTestContext(classType);

TestAssemblyInfo assemblyInfo = GetAssemblyInfo(classType);
Expand Down

0 comments on commit 333ff83

Please sign in to comment.