Skip to content

System.TypeInitializationException thrown in tests #385

@balazsosvath

Description

@balazsosvath

I have the following assembly loading logic in my architecture unit test class:

static readonly ArchUnitNET.Domain.Architecture Architecture = new ArchLoader()
    .LoadAssemblies(GetAssemblies())
    .Build();

static System.Reflection.Assembly[] GetAssemblies()
{
    var currentDir = Directory.GetCurrentDirectory();
    // Navigate up to find solution root (assumes test project is in nested folder)
    string directory = Directory.GetParent(currentDir)?.Parent?.Parent?.Parent?.FullName ?? currentDir;

    System.Reflection.Assembly[] assemblies = Directory.GetFiles(directory, "*.dll", SearchOption.AllDirectories)
        .Where(path => Path.GetFileName(path).StartsWith("ProjectName"))
        .DistinctBy(path => Path.GetFileName(path))
        .Select(assemblyPath => System.Reflection.Assembly.LoadFrom(assemblyPath))
        .ToArray();
    return assemblies;
}

When I debug the following unit test:

[Fact]
public void EngineServices_ShouldOnlyReferenceAllowedContracts()
{
    var allowedDependencies = Types().That().Are(EngineContracts)
        .Or().Are(ResourceAccessContracts)
        .Or().Are(UtilityContracts)
        .Or().Are(iFxProjects)
        .Or().DoNotResideInAssembly("*.Interface");

    var rule = Types().That().Are(EngineServices)
        .Should().OnlyDependOnTypesThat().Are(allowedDependencies)
        .Because("Engine services can only reference their own contracts, ResourceAccess contracts, Utility contracts, and iFx projects!");

    rule.Check(Architecture);
}

I get the following error:
Message:

System.TypeInitializationException : The type initializer for 'Architecture.Tests.ArchitectureTests' threw an exception.
---- System.ArgumentException : Attribute type ProjectName.iFx.Telemetry.Redaction.PersonalDataAttribute is not an attribute.

Stack Trace:

ArchitectureTests.EngineServices_ShouldOnlyReferenceAllowedContracts() line 147
InvokeStub_ArchitectureTests.EngineServices_ShouldOnlyReferenceAllowedContracts(Object, Object, IntPtr*)
MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr)
----- Inner Stack Trace -----
MonoCecilAttributeExtensions.CreateAttributeFromCustomAttribute(CustomAttribute customAttribute, TypeFactory typeFactory)
AddAttributesAndAttributeDependencies.<CreateAttributesFromCustomAttributes>b__12_1(CustomAttribute attr)
ArrayWhereSelectIterator`2.ToList(ReadOnlySpan`1 source, Func`2 predicate, Func`2 selector)
ListWhereSelectIterator`2.ToList()
AddAttributesAndAttributeDependencies.CollectMemberAttributesAndDependencies(IMember methodMember, List`1 memberCustomAttributes, List`1 attributeDependencies)
AddAttributesAndAttributeDependencies.SetUpAttributesForProperties(PropertyDefinition propertyDefinition)
EnumerableExtensions.ForEach[T](IEnumerable`1 source, Action`1[] actions)
AddAttributesAndAttributeDependencies.CollectAttributesForMembers()
AddAttributesAndAttributeDependencies.Execute()
LoadTaskRegistry.<ExecuteTasks>b__1_1(Type taskKey)
EnumerableExtensions.ForEach[T](IEnumerable`1 source, Action`1[] actions)
LoadTaskRegistry.ExecuteTasks(List`1 taskOrder)
ArchBuilder.UpdateTypeDefinitions()
ArchBuilder.Build()
ArchLoader.Build()
ArchitectureTests.cctor() line 13

I have also tried loading other assemblies as well, not just the ones which start with the ProjectName.
Then I get a different type of exception:

Message:

System.TypeInitializationException : The type initializer for 'Architecture.Tests.ArchitectureTests' threw an exception.
---- System.BadImageFormatException : Bad IL format. The format of the file 'D:\Projects\ProjectName\Host\InProc\bin\Debug\net9.0\runtimes\win-arm64\native\Microsoft.Data.SqlClient.SNI.dll' is invalid.

Stack Trace:

ArchitectureTests.EngineServices_ShouldOnlyReferenceAllowedContracts() line 147
InvokeStub_ArchitectureTests.EngineServices_ShouldOnlyReferenceAllowedContracts(Object, Object, IntPtr*)
MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr)
----- Inner Stack Trace -----
AssemblyLoadContext.LoadFromAssemblyPath(String assemblyPath)
Assembly.LoadFrom(String assemblyFile)
<>c.<GetAssemblies>b__1_1(String assemblyPath) line 26
IEnumerableSelectIterator`2.ToArray()
ArchitectureTests.GetAssemblies() line 23
ArchitectureTests.cctor() line 13

Another small thing is that without the Distinct() call another type of exception is thrown:
Message:

System.TypeInitializationException : The type initializer for 'Architecture.Tests.ArchitectureTests' threw an exception.
---- System.IO.FileLoadException : Could not load file or assembly 'ProjectName.Access.Campaigns.Interface, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. Assembly with same name is already loaded

Stack Trace:

ArchitectureTests.EngineServices_ShouldOnlyReferenceAllowedContracts() line 147
InvokeStub_ArchitectureTests.EngineServices_ShouldOnlyReferenceAllowedContracts(Object, Object, IntPtr*)
MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr)
----- Inner Stack Trace -----
AssemblyLoadContext.LoadFromAssemblyPath(String assemblyPath)
Assembly.LoadFrom(String assemblyFile)
<>c.<GetAssemblies>b__1_0(String assemblyPath) line 26
ArraySelectIterator`2.Fill(ReadOnlySpan`1 source, Span`1 destination, Func`2 func)
ArraySelectIterator`2.ToArray()
ArchitectureTests.GetAssemblies() line 23
ArchitectureTests.cctor() line 13

Is there an issue with the assembly loading logic, or is this an internal issue?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions