Moq'ing HttpContext.Current
I have a class library that has a method that sends emails based on a template. I access the template via the following:
HttpContext.Current.Server.MapPath("email template path");
Now when it comes to writing my unit tests I want to be able mock out the "Current Context", I have tried to use开发者_如何学Python the MVCMockHelpers but the "Current" property always returns null.
Is it possible to mock this property out? If so how do I go about it?
I'd consider whether you'd be better of removing the dependency on HttpContext entirely and pass the path alone into the method as a string param.
If you're also taking a dependency on HttpContext elsewhere in the same library then you need to take a dependency on HttpContextBase rather than call HttpContext directly. You should pass this in at the call site or as a constructor injected parameter.
Creating a Mock HttpContext has been covered nicely by many others including here by Craig Stuntz. This will at least get you started but will likely needed modification for your specific testing requirements.
精彩评论