【问题标题】:C# NUnit Test: Mock a external DLL-Method who call a Socket connection to a extern DeviceC# NUnit 测试:模拟调用 Socket 连接到外部设备的外部 DLL 方法
【发布时间】:2016-11-22 10:46:27
【问题描述】:

我编写了一个从设备制造商调用外部 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 吗? 如何在没有设备的情况下测试我的方法? 巫师工具能帮到我吗?

【问题讨论】:

标签: c# unit-testing dll mocking nunit


【解决方案1】:

感谢@Nkosi,我制作了一个界面:

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

以及调用静态方法并实现接口的类:

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);
    }

所以它起作用了!我希望一切都是正确的

【讨论】:

  • 是的。这正是我的建议。干得好。
猜你喜欢
  • 1970-01-01
  • 2011-02-10
  • 2021-03-12
  • 2021-10-31
  • 2023-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多