سؤال

Here's the code in my action method:

var bundleUrl = Scripts.Url("~/Scripts/MyBundle");

When i try and unit test this action method, i get the following error/stack trace:

System.ArgumentNullException
Value cannot be null.
Parameter name: httpContext
   at System.Web.HttpContextWrapper..ctor(HttpContext httpContext)
   at System.Web.Optimization.Scripts.Url(String virtualPath)

Any ideas?

I've mocked the HttpContext appropriately, as Request is filled, i can access routes, etc.

Do i need to setup the bundles? (like i do on Global.asax)

EDIT:

After using ILSpy to look at the source code for System.Web.Optimization, it appears the Scripts class creates a HttpContextWrapper from the static HttpContext.Current instance (which is null).

هل كانت مفيدة؟

المحلول

Because The Scripts class uses the static System.Web.HttpContext.Current instance, this is near impossible to mock.

So i ended up creating a wrapper interface for Scripts, then mocked that out in my unit tests.

E.g

var bundleUrl = Scripts ?? new ScriptsWrapper()..Url("~/Scripts/MyBundle");

Unit Test:

controller.Scripts = new Mock<IScripts>().Object;
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top