Larsenal Larsenal - 3 months ago 14
C# Question

How to simulate network failure for test purposes (in C#)?

I'm building what could be called the DAL for a new app. Unfortunately, network connectivity to the database is a real problem.

I'd like to be able to temporarily block network access within the scope of my test so that I can ensure my DAL behaves as expected under those circumstances.

UPDATE: There are many manual ways to disable the network, but it sure would be nice if I could enable/disable within the test itself.

Answer

For the time being, I'm just "disabling" the network by setting a bogus static IP as follows:

using System.Management;

class NetworkController
{

    public static void Disable()
    {
        SetIP("192.168.0.4", "255.255.255.0");
    }

    public static void Enable()
    {
        SetDHCP();
    }


    private static void SetIP(string ip_address, string subnet_mask)
    {
        ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
        ManagementObjectCollection objMOC = objMC.GetInstances();

        foreach (ManagementObject objMO in objMOC) {
            if ((bool)objMO("IPEnabled")) {
                try {
                    ManagementBaseObject setIP = default(ManagementBaseObject);
                    ManagementBaseObject newIP = objMO.GetMethodParameters("EnableStatic");

                    newIP("IPAddress") = new string[] { ip_address };
                    newIP("SubnetMask") = new string[] { subnet_mask };

                    setIP = objMO.InvokeMethod("EnableStatic", newIP, null);
                }
                catch (Exception generatedExceptionName) {
                    throw;
                }
            }


        }
    }

    private static void SetDHCP()
    {
        ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
        ManagementObjectCollection moc = mc.GetInstances();

        foreach (ManagementObject mo in moc) {
            // Make sure this is a IP enabled device. Not something like memory card or VM Ware
            if ((bool)mo("IPEnabled")) {
                ManagementBaseObject newDNS = mo.GetMethodParameters("SetDNSServerSearchOrder");
                newDNS("DNSServerSearchOrder") = null;
                ManagementBaseObject enableDHCP = mo.InvokeMethod("EnableDHCP", null, null);
                ManagementBaseObject setDNS = mo.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);
            }
        }
    }
}