curator curator - 1 year ago 177
C# Question

How to simulate "No Internet Connection" in Unit/Integration test in C#

I have a component that (by part) uses an internet connection. I wrote some UnitTests to ensure that to component is working. However, I would like to test the behaviour of the component without internet connections.

So, my goal is to somehow temporary disable internet, or the whole internet connection, and reactivate after test.

Any Ideas?

Answer Source

I would disable\enable like here local are connection in test initialization

SelectQuery wmiQuery = new SelectQuery("SELECT * FROM Win32_NetworkAdapter WHERE NetConnectionId != NULL");
ManagementObjectSearcher searchProcedure = new ManagementObjectSearcher(wmiQuery);
foreach (ManagementObject item in searchProcedure.Get())
    if (((string)item["NetConnectionId"]) == "Local Network Connection")
       item.InvokeMethod("Disable", null);

 // Enable local area connetcion
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download