Static methods and factories (like WebRequest.Create) are pain for unit testing. Some such factory methods allow intercepting/customizing results, some not.
The most straightforward solution is to have own factory method (preferably in form of an interface) that your code will depend on.
In some cases you can pass already created object to your code under test instead of letting code to create own.
In particular case of WebRequest.Create you may be able to provide your own factory via WebRequest.RegisterPrefix. Looking at description you will need to use some other custom Uri scheme as "http"/"https" are already registerd and duplicate registration is not allowed (also I never tried this approach).
Here is a sample code that provides custom creator for "http://" scheme in console application. This code probably will fail in case something else already registers http scheme with WebRequest:
using System;
using System.Net;
namespace CustomWebRequest
{
class Program
{
static void Main(string[] args)
{
var success = WebRequest.RegisterPrefix("http://", new CustomRequestCreator());
Console.Write("Handler registered:{0}", success);
var request = WebRequest.Create(new Uri("http://home.com"));
}
class CustomRequestCreator : IWebRequestCreate
{
public WebRequest Create(Uri uri)
{
Console.WriteLine("Custom creator");
return null; // return your mock here...
}
}
}
}
mock.Object.GetResponse()? Or you are trying to actually intercept execution ofWebRequst.Createstatic factory method?