R – Simulating connection problems for .NET HttpWebRequest


Are there ways to programmatically simulate connection problems (slow connection, response does not complete, connection gets dropped, etc.) when using the HttpWebRequest class?


EDIT: To elaborate more, I need this for debugging but would want to turn it into a test eventually. I'm using the async methods BeginGetRequestStream, EndGetRequestStream, BeginGetResponse and EndGetResponse. I have wrapped them all in proper (I hope) Try Catch blocks which log the exceptions that happen.

I know this works for some cases (e.g. when I pull out the network cable). But on some rare occasions (i.e. only when the website I'm requesting is slow) then my system crashes and I get this in the Event Log

Exception: System.Net.WebException

Message: The request was aborted: The connection was closed unexpectedly.

StackTrace:    at System.Net.ConnectStream.BeginRead(Byte[] buffer, Int32 offset, Int32 size, AsyncCallback callback, Object state)
   at System.IO.Compression.DeflateStream.ReadCallback(IAsyncResult baseStreamResult)
   at System.Net.LazyAsyncResult.Complete(IntPtr userToken)
   at System.Net.ContextAwareResult.CompleteCallback(Object state)
   at System.Threading.ExecutionContext.runTryCode(Object userData)
   at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Net.ContextAwareResult.Complete(IntPtr userToken)
   at System.Net.LazyAsyncResult.ProtectedInvokeCallback(Object result, IntPtr userToken)
   at System.Net.Sockets.BaseOverlappedAsyncResult.CompletionPortCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
   at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)

I am making an assumption it's from HttpWebRequest but then again all my code is wrapped in Try Catch blocks.

Would mocks help in such a case?

Best Solution

@Chris Unfortunately, Microsoft neglected to make many of the BCL objects easily mockable, as they tend to use abstract classes, and .NET classes are closed by design (in other words, for a method to be overridden by a subclass, it needs to be explicitly marked as virtual), whereas Java is open by design (that is, a subclass can override any method, unless they are marked as final). Using interfaces or marking the methods as virtual would have saved a lot of headaches in the testing space. Microsoft may have the testability religion now (e.g. ASP.NET MVC), but it's a bit late for the BCL.

Typemock Isolator may be able to help, but I don't believe Moq can, in this case.