Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET NUnit test - Assembly.GetEntryAssembly() is null

When class used Assembly.GetEntryAssembly() run in unit test, the Assembly.GetEntryAssembly() is null.

Is there some option how define Assembly.GetEntryAssembly() during unit testing?

like image 248
Simon Avatar asked Dec 02 '10 16:12

Simon


2 Answers

Implement the SetEntryAssembly(Assembly assembly) method given in

http://frostwave.googlecode.com/svn-history/r75/trunk/F2DUnitTests/Code/AssemblyUtilities.cs

to your unit test project.

         /// <summary>
        /// Use as first line in ad hoc tests (needed by XNA specifically)
        /// </summary>
        public static void SetEntryAssembly()
        {
            SetEntryAssembly(Assembly.GetCallingAssembly());
        }

        /// <summary>
        /// Allows setting the Entry Assembly when needed. 
        /// Use AssemblyUtilities.SetEntryAssembly() as first line in XNA ad hoc tests
        /// </summary>
        /// <param name="assembly">Assembly to set as entry assembly</param>
        public static void SetEntryAssembly(Assembly assembly)
        {
            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);
        }
like image 117
Manjay_TBAG Avatar answered Nov 09 '22 02:11

Manjay_TBAG


You could do something like this with Rhino Mocks: Encapsulate the Assembly.GetEntryAssembly() call into a class with interface IAssemblyLoader and inject it into the class your are testing. This is not tested but something along the lines of this:

[Test] public void TestSomething() {
  // arrange
  var stubbedAssemblyLoader = MockRepository.GenerateStub<IAssemblyLoader>();
  stubbedAssemblyLoader.Stub(x => x.GetEntryAssembly()).Return(Assembly.LoadFrom("assemblyFile"));

  // act      
  var myClassUnderTest = new MyClassUnderTest(stubbedAssemblyLoader);
  var result = myClassUnderTest.MethodToTest();

  // assert
  Assert.AreEqual("expected result", result);
}

public interface IAssemblyLoader {
  Assembly GetEntryAssembly();
}
public class AssemblyLoader : IAssemblyLoader {
  public Assembly GetEntryAssembly() {
    return Assembly.GetEntryAssembly();
  }
}
like image 28
Luke Hutton Avatar answered Nov 09 '22 04:11

Luke Hutton