Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

moq HttpWebRequest object

Tags:

c#

mocking

moq

I wanted to try Moq to mock a request object for simulating things like network failure on in my test cases. My first attempt was:

        var mock = new Mock<WebRequest>();
        mock.Setup(m => m.GetResponse()).Throws<WebException>();
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
        //trying to get this to throw a web exception
        request.GetResponse();

This is not working so I'm looking for the correct way to do this.

Thanks

EDIT: as pointed out in the comments I'd like to use WebRequest.Create (it's actually in another method but I've simplified for the example).

like image 696
probably at the beach Avatar asked Jun 04 '26 11:06

probably at the beach


1 Answers

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...
            }
        }
    }
}
like image 183
Alexei Levenkov Avatar answered Jun 07 '26 23:06

Alexei Levenkov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!