模拟网络故障

时间:2014-08-14 23:20:32

标签: c# unit-testing networking testing

我使用webservice编写了一个应用程序,我想模拟网络故障以进行测试。我知道我可以手动关闭网络,但如果会自动关闭它会很棒。

我尝试了来自Larsenal的How to simulate network failure for test purposes (in C#)?解决方案,但它没有识别出ManagementClass / ObjectCollection / ......而且我不知道为什么(我使用的是System.Managment.Man。 ..它仍然没有用。我输入了所需的参考资料 - 没有工作。我不知道我做错了什么。

应该是这样的:

[TestMethod]
public void Service_Login_NoInternetConnection()
{
  // Some code...
  TurnOffNetworkConnection();
  // More code...
  TurnOnNetworkConnection();
  // Blablabla code...
}

1 个答案:

答案 0 :(得分:1)

您可以使用WMI。

首先确保添加引用:System.Management

然后我得到所有设备:
“ManagementObjectSearcher searcher = new ManagementObjectSearcher(”root \ CIMV2“,”SELECT * FROM Win32_NetworkAdapterConfiguration“);”

现在我需要检查设备是否有DHCPLeaseObtained 所以我使用foreach来检查搜索器中的每个网络设备:
String Check = Convert.ToString(queryObj [“DHCPLeaseObtained”]);

如果设备没有DHCPLeaseObtained,则字符串将为emty。 所以我检查字符串是否为emty:
if(String.IsNullOrEmpty(Check))

然后你可以在else中使用ReleaseDHCPLease和RenewDHCPLease ManagementBaseObject outParams = queryObj.InvokeMethod(“ReleaseDHCPLease”,null,null);

ManagementBaseObject outParams = queryObj.InvokeMethod(“RenewDHCPLease”,null,null);

using System.Management;


    public void TurnOnNetworkConnection()
{

        try
        {
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_NetworkAdapterConfiguration");

               foreach (ManagementObject queryObj in searcher.Get())
               {
                  String Check = Convert.ToString(queryObj["DHCPLeaseObtained"]);
                  if (String.IsNullOrEmpty(Check))
                    {
                    }
                    else
                    {
                    ManagementBaseObject outParams = queryObj.InvokeMethod("RenewDHCPLease", null, null);
                    }
               }
         }
           catch (ManagementException e)
           {
           MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);
           }
}

    public void TurnOffNetworkConnection()
{
        try
        {
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_NetworkAdapterConfiguration"); 

            foreach (ManagementObject queryObj in searcher.Get())
            {
                String Check = Convert.ToString(queryObj["DHCPLeaseObtained"]);
                if (String.IsNullOrEmpty(Check)) 
                {
                }
                else
                {
                    ManagementBaseObject outParams = queryObj.InvokeMethod("ReleaseDHCPLease", null, null);
                }
            }
        }
        catch (ManagementException e)
        {
            MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);
        }
}