Reputation: 659
I use asp.net mvc3/razor with dbfirst model. I send a confirmation email after registration that is in a xml format. I need to read this xml file while unit testing, I get null reference error as httpcontext.current is null.I tried to mock it, but again I get a error saying "value cannot be null" This is my code, please help:
accountcontroller:
Fds.ReadXml(HttpContext.Current.Server.MapPath("~/Files/ForgotPassword.xml"));
unit testing:
public void Saveuser()
{
RegisterModel model = new RegisterModel();
FormCollection f = new FormCollection();
List<MailModel> m = new List<MailModel>();
HttpContext.Current = FakeHttpContext();
m = user.GetMail().ToList();
MailModel mmodel = new MailModel();
mmodel = m[0];
model.Name = "testuse11r9788";
model.UserName = "test1user9878";
model.Password = "1234567";
model.ConfirmPassword = "1234567";
model.Email = "[email protected]";
var controller = new AccountController(user,mail);
var saveuser = controller.Register(model,f) as ViewResult;
var saveActUser = (RegisterModel)saveuser.ViewData.Model;
var saveExpUser = model;
areuserEqual(saveExpUser, saveActUser);
}
public static HttpContext FakeHttpContext()
{
//please help me what should be entered in httprequest????
var httpRequest = new HttpRequest("", "http://localhost:mmmm/", "");
var stringWriter = new StringWriter();
var httpResponce = new HttpResponse(stringWriter);
var httpContext = new HttpContext(httpRequest, httpResponce);
var sessionContainer = new HttpSessionStateContainer("id", new SessionStateItemCollection(),
new HttpStaticObjectsCollection(), 10, true,
HttpCookieMode.AutoDetect,
SessionStateMode.InProc, false);
httpContext.Items["AspSession"] = typeof(HttpSessionState).GetConstructor(
BindingFlags.NonPublic | BindingFlags.Instance,
null, CallingConventions.Standard,
new[] { typeof(HttpSessionStateContainer) },
null)
.Invoke(new object[] { sessionContainer });
return httpContext;
}
Upvotes: 0
Views: 1898
Reputation: 5899
You need to abstract out the loading of the XML file.
Such as;
class WebContentLocator : IContentLocator{
public string GetPath(string relativePath) {
return HttpContext.Current.Server.MapPath(relativePath);
}
}
class TestContentLocator : IContentLocator{
string _contentRoot;
public TestContentLocator() {
_contentRoot = ConfigurationManager.AppSettings["ContentRoot"];
}
public string GetPath(string relativePath) {
return Path.Combine(_contentRoot, relativePath.Replace("~", string.empty);
}
}
interface IContentLocator {
string GetPath(string relativePath);
}
and in your test inject the TestContentLocator into the code that is doing the XML loading, which would by default be using the WebContentLocator.
Fds.ReadXml(_contentLocator.Get("~/Files/ForgotPassword.xml"));
Upvotes: 3