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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With