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

前端 未结 2 2038
时光说笑
时光说笑 2020-12-01 10:31

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

Is there some option h

相关标签:
2条回答
  • 2020-12-01 11:03

    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();
      }
    }
    
    0 讨论(0)
  • 2020-12-01 11:05

    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);
            }
    
    0 讨论(0)
提交回复
热议问题