P.Brian.Mackey
P.Brian.Mackey

Reputation: 44285

Unit test method with HttpContext

    public SupportedBrowser GetBrowser()
    {
        string agent = HttpContext.Current.Request.Headers["User-Agent"];

        if (agent.Contains("iPad"))
        {
            return new iPad();
        }
        else
            return new InternetExplorer7();
    }

I setup a unit test for the method above using Microsofts unit test tool (MS-Test?). Because the unit test is not a web site, there is no HttpContext. I can think of two solutions:

A. Add an optional param: GetBrowser(bool debug = false). This allows current code to execute without refactor. Then modify the method to create a mock context or hard coded user-agent when debug is true.

B. Add Dependency injection. Get the context from somewhere else. Though, I think I'll need to drop in IoC via ninject to get this automated. Thats a lot of work.

Can you think of something better or improve upon these ideas?

Note, this method is housed in a class library. I want to keep it that way.

Upvotes: 0

Views: 1266

Answers (1)

Rick Liddle
Rick Liddle

Reputation: 2714

Your agent string is a natural place for mocking. Instead of getting the agent string from the request context inside this method, pass it or inject to the method/class. That way you've got control over it during testing and runtime.

Upvotes: 2

Related Questions