Skip to content
This repository has been archived by the owner on Dec 14, 2018. It is now read-only.

UrlHelperFactory.GetUrlHelper may throw an exception #5170

Closed
vdachev opened this issue Aug 22, 2016 · 1 comment
Closed

UrlHelperFactory.GetUrlHelper may throw an exception #5170

vdachev opened this issue Aug 22, 2016 · 1 comment
Assignees

Comments

@vdachev
Copy link

vdachev commented Aug 22, 2016

While trying to mock a controller I came across a KeyNotFoundException in the UrlHelperFactory's GetUrlHelper method.

It seems the following code relies on the typeof(IUrlHelper) key already populated in the Items collection:

// Perf: Create only one UrlHelper per context
var urlHelper = httpContext.Items[typeof(IUrlHelper)] as IUrlHelper;
if (urlHelper == null)
{
   urlHelper = new UrlHelper(context);
   httpContext.Items[typeof(IUrlHelper)] = urlHelper;
}

If the key is missing, this line throws an exception, instead of returning null. I believe that the following code should be used instead:

// Perf: Create only one UrlHelper per context
object urlHelper;
if (!httpContext.Items.TryGetvalue(typeof(IUrlHelper), out urlHelper)
    || !(urlHelper is IUrlHelper))
{
    urlHelper = new UrlHelper(context);
    httpContext.Items[typeof(IUrlHelper)] = urlHelper;
}

return (IUrlHelper)urlHelper;
@rynowak
Copy link
Member

rynowak commented Aug 22, 2016

Did you create a mock for HttpContext.Items? Right now this code expects Items to return null on a missing key, which is something we should probably fix since it's specified as IDictionary<>.

Regardless, I'd strongly suggest using DefaultHttpContext in your tests - you'll need less mock setup stuff. It's what we do and we haven't run into any limitations.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

4 participants