简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM