繁体   English   中英

如何模拟DLL导入

[英]How to mock a DLL Import

我正在尝试编写使用Dll导入的类的单元测试用例,如下所示

 [DllImport("user32.dll")]
 public static extern IntPtr FindWindow(string name, string windowName);

为了测试该类,我想使用最小起订量来模拟上面的语句,但无法弄清楚如何为其设置模拟。

也想知道以上是否可以实现。如果不是,那么需要做些什么才能使其可测试。

我知道要使该类可测试,我们需要在这些语句上创建包装器,并且需要将其分离到单独的类中。

想知道是否有其他选择可以实现相同目标。

实际上,您可以使用typemock隔离器从导出的Dll中模拟方法,而无需在代码中进行任何不必要的更改。 您只需要导出Dll并像其他任何静态方法一样模拟该方法,例如:

public class ClassUnderTest
    {

        public bool foo()
        {
            if(Dependecy.FindWindow("bla","bla") == null)
            {
                throw new Exception();
            }
            return true;
        }
    }

public class Dependecy
{//imported method from dll
     [DllImport("user32.dll")]
     public static extern IntPtr FindWindow(string name, string windowName);
 }

        [TestMethod]
        public void TestMethod1()
        {
            //setting a mocked behavior for when the method will be called
            Isolate.WhenCalled(() => Dependecy.FindWindow("", "")).WillReturn(new IntPtr(5));

            ClassUnderTest classUnderTest = new ClassUnderTest();
            var res = classUnderTest.foo();

            Assert.IsTrue(res);
        }

您可以在此处查看有关Pinvoked方法的更多信息

您不能模拟静态方法,而只能模拟具有虚拟成员的接口或类。 但是,您可以将方法包装为可以包装的虚拟方法:

interface StaticWrapper
{
    InPtr WrapStaticMethod(string name, string windowName);
}
class MyUsualBehaviour : IStaticWrapper
{
    public InPtr WrapStatic(string name, string windowName)
    {
        // here we do the static call from extern DLL
        return FindWindow(name, widnowName);
    }
}

但是,您现在可以模拟该接口,而不是静态方法:

var mock = new Moq<IStaticWrapper>();
mock.Setup(x => x.WrapStatic("name", "windowName")).Returns(whatever);

此外,您不会在代码中调用extern方法,而只会调用包装器,该包装器可减少与特定库的代码耦合。

请参阅此链接以进一步了解构想: http : //adventuresdotnet.blogspot.de/2011/03/mocking-static-methods-for-unit-testing.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM