'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.



Solution 1:[1]

There are many ways in which the system could have "No Internet" and the answer really depends on what you mean.

As the accepted other answer suggests, you could simply disable the network interface. That guarantees you have no internet, but the computer also will know it has no network either.

A couple other options are

  1. To remove your Default Gateway (this may require setting static IP settings in the control panel, though I'm sure you could do it programmatically as well)

This way, the computer still thinks it's connected, but it won't have any network access except on the local subnet

  1. Remove DNS server settings, see above link.

This way, the computer has direct IP based access but to a regular user it would appear as if there was "no internet."

Solution 2:[2]

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

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

 [ClassCleanup()]
 // Enable local area connetcion

Solution 3:[3]

Whilst not a direct answer to your question I believe you may find some use in this tool - https://jagt.github.io/clumsy/download

I've used it at work to simulate different network conditions for an mobile app that I'm currently working on. It is possible to completely disable the network connection by setting packet drop to 100%.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Calpurnio Pisone
Solution 2 Community
Solution 3 Tom Biddulph