I have a .NET 8 test project (xUnit), called MyCompany.MyProject.Test
.
How do I get the test project's Assembly
?
I tried:
Assembly.GetEntryAssembly()
: it gets testhost
;Assembly.GetExecutingAssembly()
: it gets the assembly of the method I'm in, not the test project's assembly;MyCompany.*
assemblies) doesn't seem to bring me any closer to something from my company, I only get more System.*
and Microsoft.*
assemblies.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.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
using System.Reflection;
namespace MyCompany.MyProject;
public class Class1
{
public static IEnumerable<Assembly> GetAssemblies() => AppDomain.CurrentDomain.GetAssemblies();
}
<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>
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();
}