2016-11-30 130 views
-1

我试图写它采用DLL输入像下面如何嘲笑一个DLL导入

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

为了测试我想嘲笑起订量使用上述声明的类的类的单元测试用例,但无法弄清楚如何为它设置一个模拟。

也想知道上面是否达到或not..if不那么需要什么才能完成,使其可测试。

我知道,使这个类可测试,我们需要创建在这些语句包装和需要它在一个单独的类分开。

想知道是否有任何其他选项,以达到同样的。

+0

但随着DLL进口静电是必须 –

+0

当然,但您可以将对该静态方法的调用隐藏到另一个方法的调用中。 – HimBromBeere

+0

Yes..but然后当我尝试写单元测试为包装类,我会在同样的情况 –

回答

1

你不能模拟静态方法,而只能使用虚拟成员的接口或类。但是你可以用该方法成一个虚拟的,你可以换:

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

+0

我知道...这就是我在我的问题中提到的.. –

+1

@RishiTiwari为什么你不这样做呢?你所要求的等同于“我怎样才能嘲笑装配参考”? DllImport不是模拟的方法,它是*声明* - 对库中特定入口点的引用。在单个类中收集DllImport声明实际上是一种很好的做法。 –

+0

我只是想知道是否有可能或不嘲笑一个DLL导入...使其可测试我知道的包装是必须的,感谢反正 –

2

其实你可以通过使用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方法here

+0

我想要使用MOQ来做同样的事情。我们正在使用MOQ框架来模拟我们的依赖关系...不能使用任何其他框架......但是,如果我们使用Type mocks,我们实际上可以模拟DLL导入调用,但是要感谢您。我们投了您的答案,但不能将其标记为答案。 –