0
    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.

P.Brian.Mackey
  • 39,360
  • 59
  • 210
  • 327

1 Answers1

2

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.

Rick Liddle
  • 2,668
  • 18
  • 30
  • I like DI, but as I posted in my question I think this is going to be quite a bit of work. Since the HttpContext.Request.UserAgent is readonly I cant set for testing. I may need to go all out using something akin to mallows98's answer here http://stackoverflow.com/questions/1452418/how-do-i-mock-the-httpcontext-in-asp-net-mvc-using-moq. Trying to avoid that route. – P.Brian.Mackey Jul 13 '11 at 19:26
  • 1
    Don't inject the context, inject the agent string. That will give you total control over it. – Rick Liddle Jul 13 '11 at 19:28
  • @Rick Liddle - +1 oh haha. Simple, as most great ideas are. Thanks. – P.Brian.Mackey Jul 13 '11 at 19:32
  • Sometimes all it takes to see the solution is a different set of eyeballs. :-) – Rick Liddle Jul 13 '11 at 19:33