问题描述
当使用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() 为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!