我正在尝试编写一个使用Dll导入的类的单元测试用例,如下所示
[DllImport("user32.dll")]
public static extern IntPtr FindWindow(string name, string windowName);为了测试这个类,我想使用MOQ模拟上面的语句,但是不知道如何为它设置一个模拟。
我也想知道是否上述是可实现的或not..if,然后需要做什么,以使其可测试。
我知道,为了使这个类可测试,我们需要在这些语句上创建包装器,并且需要在一个单独的类中将其分离出来。
我想知道有没有其他选择可以达到同样的效果。
发布于 2016-12-01 17:44:13
实际上,您可以使用类型锁隔离器从导出的Dlls中模拟方法,而无需对代码进行任何不必要的更改。您只需导出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);
}您可以看到更多关于about方法here的信息
发布于 2016-11-30 18:09:55
你不能模拟静态方法,只能模拟具有虚拟成员的接口或类。但是,您可以将该方法包装到一个可以包装的虚拟方法中:
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
https://stackoverflow.com/questions/40885310
复制相似问题