Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 978
curator Avatar asked Aug 03 '16 19:08

curator


2 Answers

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
like image 190
Shachaf.Gortler Avatar answered Oct 06 '22 20:10

Shachaf.Gortler


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

like image 27
Nate Avatar answered Oct 06 '22 19:10

Nate