2013-08-19 2 views
0

dbfirst 모델과 함께 asp.net mvc3/razor를 사용합니다. xml 형식으로 등록한 후 확인 이메일을 보내드립니다. 단위 테스트 중에이 xml 파일을 읽어야합니다. httpcontext.current가 null 인 경우 null 참조 오류가 발생합니다. 모의하려고했지만 "null 값일 수 없습니다"라는 오류가 발생합니다. 이것은 내 코드입니다. 도와주세요 :httpcontext.current.server.mappath 및 단위 테스트

accountcontroller :

Fds.ReadXml(HttpContext.Current.Server.MapPath("~/Files/ForgotPassword.xml")); 

단위 테스트 :

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() 
     { 

// 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; 
     } 

답변

3

XML 파일로드를 추상화해야합니다.

;

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); 
} 

및 테스트에

는 기본적으로 WebContentLocator을 사용하고있을 것이다 XML 로딩을 수행하는 코드로 TestContentLocator를 주입.

Fds.ReadXml(_contentLocator.Get("~/Files/ForgotPassword.xml"));