开发者

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 de开发者_如何学运维bug 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜