Davweiss
Davweiss

Reputation: 51

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

I have written a Program who call an external DLL-Method from the Device-Manufacturer. This Methods (round about 600) makes an Ethernet Connection to a Device. The Methods looks like this:

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

and this:

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

Now I want to write Unit-Test for my Code and want to mock the DLL-Methods. The DLL is written in C and with the Library has come a C# file (See Methods above). My Methods looks like this:

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

Can you tell me how to write a Mock für this external DLL? How can I Test my Methods without the Device? Witch tools can help me?

Upvotes: 2

Views: 2064

Answers (1)

Davweiss
Davweiss

Reputation: 51

Thaks to @Nkosi I have made an Interface:

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

and a Class who who call the static methods and implements the Interface:

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

and a test like this:

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

So it works! I hope it is all correct

Upvotes: 3

Related Questions