且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

.NET NUnit 测试 - Assembly.GetEntryAssembly() 为空

更新时间:2023-02-10 22:57:38

你可以用 Rhino Mocks 做这样的事情:将 Assembly.GetEntryAssembly() 调用封装到一个带有接口 IAssemblyLoader 的类中,并将它注入到你正在测试的类中.这未经测试,但大致如下:

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();
  }
}