Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set EntryAssembly for tests in .Net Core

I am currently migrating a project and it's test projects from .Net Framework to .Net Core.

In .Net Framework, we used to be able to do something like this to set the EntryAssembly for tests :

AppDomainManager manager = new AppDomainManager();
FieldInfo entryAssemblyfield = manager.GetType().GetField("m_entryAssembly", BindingFlags.Instance | BindingFlags.NonPublic);
entryAssemblyfield.SetValue(manager, assembly);

AppDomain domain = AppDomain.CurrentDomain;
FieldInfo domainManagerField = domain.GetType().GetField("_domainManager", BindingFlags.Instance | BindingFlags.NonPublic);
domainManagerField.SetValue(domain, manager);

Taken from here : https://dejanstojanovic.net/aspnet/2015/january/set-entry-assembly-in-unit-testing-methods/

Since AppDomainManager is not available in .Net Core anymore, how can we accomplish something similar so that Assembly.GetEntryAssembly(); returns what I want instead of the tests project assembly.

like image 481
Simon Foley Avatar asked Mar 09 '20 16:03

Simon Foley


Video Answer


1 Answers

Here are two possible solutions I found :

1) Like @ajz suggested, you can create an interface with a GetEntryAssembly method that returns Assembly.GetEntryAssembly() that you could Mock/Setup to return whatever you want for your tests.

2) You can create a class with GetEntryAssembly Func like this :

public static class AssemblyHelper
{
    public static Func<Assembly> GetEntryAssembly = () => Assembly.GetEntryAssembly();
}

In your test method you can override this behavior by reassigning an in-line function to it :

AssemblyHelper.GetEntryAssembly = () => assembly;

We went with the second solution simply because we used to call Assembly.GetEntryAssembly() inside a static constructor and I don't think there's anyway I can mock an object and set it to a field before going through that.

like image 104
Simon Foley Avatar answered Sep 28 '22 06:09

Simon Foley