Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking HttpListenerContext

Tags:

c#

I'm trying to unit test some code that uses HttpListenerContext. I cant find a base class or an interface I can mock. Is there anything like HttpRequestBase for HttpListenerContext?

like image 571
Tom Squires Avatar asked Feb 26 '13 14:02

Tom Squires


1 Answers

The way to solve the problem is to create an abstract class with virtual methods.

public abstract class HttpListenerContextBase
{
    public virtual HttpListenerRequestBase Request { get; private set; }
    public virtual HttpListenerResponseBase Response { get; private set; }
    public virtual IPrincipal User { get; private set; }
}

You can then create your own wrapper class for the real one that accepts HTTPListnerContext in the constructor and inherits from HttpListenerContextBase. It just returns the methods from the real context.

In your code you then write all your methods against HttpListenerContextBase and inject in a mocked one.

Bit of effort but gets you to something testable.

like image 73
Tom Squires Avatar answered Nov 09 '22 22:11

Tom Squires