Brunov's blog

Sergey Vyacheslavovich Brunov's blog

TDD: Mocking System.Net.WebClient

2013-07-30 08:22:56 Moscow time

Writing unit-test for the class that uses System.Net.WebClient, I have found out that there is no possibility to mock System.Net.WebClient using dynamic mock object frameworks (like RhinoMocks and Moq) because its methods are not virtual.

The solution is to introduce web client interface and abstract factory interface to create such web clients.

interface IWebClient : IDisposable
{
    // Required methods (subset of `System.Net.WebClient` methods).
    byte[] DownloadData(Uri address);
    byte[] UploadData(Uri address, byte[] data);
}

interface IWebClientFactory
{
    IWebClient Create();
}

The default implementations for System.Net.WebClient are straight-forward:

/// <summary>
/// System web client.
/// </summary>
public class SystemWebClient : WebClient, IWebClient
{

}

/// <summary>
/// System web client factory.
/// </summary>
public class SystemWebClientFactory : IWebClientFactory
{
    #region IWebClientFactory implementation

    public IWebClient Create()
    {
        return new SystemWebClient();
    }

    #endregion
}

Now IWebClientFactory interface can be injected as a dependency (constructor injection) and the dependent classes can be tested.

Tags: C# TDD