本文介绍了.NET NUnit 测试 - Assembly.GetEntryAssembly() 为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用Assembly.GetEntryAssembly() 的类在单元测试中运行时,Assembly.GetEntryAssembly()null.

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

在单元测试期间是否有一些选项如何定义 Assembly.GetEntryAssembly()?

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

推荐答案

你可以用 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();
  }
}

这篇关于.NET NUnit 测试 - Assembly.GetEntryAssembly() 为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 23:40