03 November 2014

Few days ago I needed to write some tests for code that does some web calls and System.Net.WebRequest is used for the job.

I was already thinking how I’ll remove all the WebRequests calls and abstract them, then in my unit tests I’d able to use mocked implementation.

Looking into the WebRequest interface, I’ve found

 public static bool RegisterPrefix(string prefix, IWebRequestCreate creator);

With registering a prefix I could achieve just that, using my own implementation of WebRequest for tests.

Several classes needed to be implemented

MockedWebRequestCreate : IWebRequestCreate
MockedWebRequest : WebRequest
MockedWebReponse : WebResponse

Just register prefix in your SetUp method

public void Setup()
    WebRequest.RegisterPrefix("tst", new MockedWebRequestCreate());

Now just create a web call with Uri tst://demo.server/ and our MockedWebRequestCreate is used!

This really saved my time and I haven’t cause any damage to the design of my app.

blog comments powered by Disqus