0

How would I go about recreating a "The specified network name is no longer available" exception for testing.

The following code below is trying to copy a file on the same network. If the connection to the network is lost, I would like to recall the CopyFile method and try running it after a couple seconds before throwing the exception. What would be the most easiest way to test this exception?

private void CopyFile()
{
    int numberOfExecution = 0;
    bool copying = true;

    while (copying)
    {
        copying = false;

        try
        {
            File.Copy(file1, file2);
        }
        catch (Exception ex)
        {
            if (ex.Message.Contains("The specified network name is no longer available"))
            {
                numberOfExecution += 1;
                System.Threading.Thread.Sleep(5000);

                if (numberOfExecution >= 5)
                {
                    throw ex;
                }

                copying = true;
            }
            else
            {
                throw ex;
            }
        }
        finally
        {

        }
    }
}
User11040
  • 208
  • 1
  • 3
  • 12
  • 1
    https://stackoverflow.com/questions/1087351/how-do-you-mock-out-the-file-system-in-c-sharp-for-unit-testing ... – Alexei Levenkov Jan 29 '18 at 22:20
  • 1
    Try to avoid catching `Exception` if possible (use a more derived type) and don't `throw ex;` as it destroys the stacktrace, just use `throw;` instead. – pinkfloydx33 Jan 29 '18 at 22:29
  • If you log Exception.ToString(), you can see exactly what exception is throwing that particular message, then just throw that where you need to simulate that happening in a real-world scenario. – afilbert Jan 29 '18 at 22:32

1 Answers1

0

The idea is to create a test where File.Copy resolves to a static method you've set up for testing purposes and not to System.IO.File.Copy. In other words, you mock File.Copy.

You can tailor this method to cover all cases; succeed on first try, fail at first and succeed later on, or fail on all tries.

The fact that it doesn't really copy anything and simply returns or throws is irrelevant to the method you are testing.

My advice, use an existing tool to do this; Alexei's comment points you in the right direction.

InBetween
  • 32,319
  • 3
  • 50
  • 90