.net-core

How do I get my test project's assembly when I write a unit test?


I have a .NET 8 test project (xUnit), called MyCompany.MyProject.Test.

How do I get the test project's Assembly?

I tried:


Solution

  • Creating a minimal example with a new library project MyCompany.MyProject referenced by a new test project MyCompany.MyProject.Test see below, both tests in UnitTest1 pass.

    That means the test assembly is in the list returned by AppDomain.CurrentDomain.GetAssemblies() as expected. It doesn't matter if the call is in the test code or the tested code.

    MyCompany.MyProject

    MyCompany.MyProject.csproj

    <Project Sdk="Microsoft.NET.Sdk">
    
      <PropertyGroup>
        <TargetFramework>net8.0</TargetFramework>
        <ImplicitUsings>enable</ImplicitUsings>
        <Nullable>enable</Nullable>
      </PropertyGroup>
    
    </Project>
    

    Class1.cs

    using System.Reflection;
    
    namespace MyCompany.MyProject;
    
    public class Class1
    {
        public static IEnumerable<Assembly> GetAssemblies() => AppDomain.CurrentDomain.GetAssemblies();
    }
    
    

    MyCompany.MyProject.Test

    MyCompany.MyProject.Test.csproj

    <Project Sdk="Microsoft.NET.Sdk">
    
      <PropertyGroup>
        <TargetFramework>net8.0</TargetFramework>
        <ImplicitUsings>enable</ImplicitUsings>
        <Nullable>enable</Nullable>
    
        <IsPackable>false</IsPackable>
        <IsTestProject>true</IsTestProject>
      </PropertyGroup>
    
      <ItemGroup>
        <PackageReference Include="coverlet.collector" Version="6.0.0" />
        <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
        <PackageReference Include="xunit" Version="2.5.3" />
        <PackageReference Include="xunit.runner.visualstudio" Version="2.5.3" />
      </ItemGroup>
    
      <ItemGroup>
        <ProjectReference Include="..\MyCompany.MyProject\MyCompany.MyProject.csproj" />
      </ItemGroup>
    
      <ItemGroup>
        <Using Include="Xunit" />
      </ItemGroup>
    
    </Project>
    
    

    UnitTest1.cs

    using System.Reflection;
    
    namespace MyCompany.MyProject.Test;
    
    public class UnitTest1
    {
        [Fact]
        public void UnitTest1_GetAssemblies_ContainsTestAssembly()
        {
            var AssembliesFromUnitTest1 = UnitTest1.GetAssemblies();
            Assert.Contains(AssembliesFromUnitTest1, assembly => assembly.GetName().Name == "MyCompany.MyProject.Test");
        }
    
        [Fact]
        public void Class1_GetAssemblies_ContainsTestAssembly()
        {
            var AssembliesFromClass1 = Class1.GetAssemblies();
            Assert.Contains(AssembliesFromClass1, assembly => assembly.GetName().Name == "MyCompany.MyProject.Test");
        }
    
        public static IEnumerable<Assembly> GetAssemblies() => AppDomain.CurrentDomain.GetAssemblies();
    }