gpt4 book ai didi

C# NUnit 测试 : Mock a external DLL-Method who call a Socket connection to a extern Device

转载 作者:行者123 更新时间:2023-11-30 23:18:40 25 4
gpt4 key购买 nike

我编写了一个从设备制造商调用外部 DLL 方法的程序。此方法(大约 600 个)建立到设备的以太网连接。方法看起来像这样:

[DllImport("Libary.dll", EntryPoint = "methode1")]
public static extern short methode1(ushort Handl,
short a, short b, short c, short d, [Out, MarshalAs(UnmanagedType.LPStruct)] SpecialStruct1 e);

还有这个:

[DllImport("Libary.dll", EntryPoint = "methode2")]
public static extern short methode2(ushort Handl, short a, int b);

现在我想为我的代码编写单元测试并模拟 DLL 方法。DLL 是用 C 编写的,库中有一个 C# 文件(参见上面的方法)。我的方法如下所示:

public int myMethode1(ushort handl, List<object> parameters)
{
int a = (int)parameters[1];
string b = (string)parameters[2];
return Libary1.Methode1(handl, ref a, b);
}

你能告诉我如何为这个外部 DLL 编写 Mock 吗?如何在没有设备的情况下测试我的方法?女巫工具可以帮助我吗?

最佳答案

感谢@Nkosi 我做了一个界面:

public interface ILibary
{
short Methode1(ushort FlibHndl, [Out, MarshalAs(UnmanagedType.LPStruct)] RealLibary.Struct1 a);
}

和调用静态方法并实现接口(interface)的类:

class Libary: ILibary
{
public short Methode1 (ushort FlibHndl, [Out, MarshalAs(UnmanagedType.LPStruct)] RealLibary.Struct1 a)
{
return RealLibary.Methode1(FlibHndl, a);
}
}

和这样的测试:

    [Test]
public void Libary1_Methode1_struct()
{
Speed speed = new Speed(new CommInterface());
int response = 99;
Mock<ILibary> mockLibary = new Mock< ILibary>();

mockLibary.Setup(
r =>
r. Methode1(It.IsAny<ushort>(), It.IsAny<short>(), It.IsAny<short>(), It.IsAny<RealLibary.Struct1>()))
.Callback<ushort, short, short, RealLibary.Struct1>(
(hndl, a, b, dbaxis) =>
{
dbaxis.data = new[] {0, 1, 2, 3};
dbaxis.dummy = 0;
dbaxis.type = 0;
});

RealLibary.Struct1 struct1 = new RealLibary.Struct1();
List<object> list = new List<object>();
list.Add(new short());
list.Add(struct1);
list.Add(new short());
list.Add(new short());
speed.Methode1(0, mockLibary.Object, list, out response);

Assert.AreEqual(4, struct1.data.Length);
}

原来如此!我希望一切都是正确的

关于C# NUnit 测试 : Mock a external DLL-Method who call a Socket connection to a extern Device,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40739816/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com