如何为测试目的模拟网络故障(在 C# 中)? [英] How to simulate network failure for test purposes (in C#)?

查看:29
本文介绍了如何为测试目的模拟网络故障(在 C# 中)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为新应用构建可称为 DAL 的东西.不幸的是,与数据库的网络连接是一个真正的问题.

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

我希望能够在我的测试范围内临时阻止网络访问,以便我可以确保我的 DAL 在这些情况下按预期运行.

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.

推荐答案

暂时,我只是通过设置一个虚假的静态 IP 来禁用"网络,如下所示:

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

这篇关于如何为测试目的模拟网络故障(在 C# 中)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆