나는 (자습서 Create an ASP.NET MVC 5 App with Facebook and Google OAuth2 and OpenID Sign-on (C#) 참조) 새 속성을 추가하여 ApplicationUser 클래스를 확장하고있어단위 테스트 ASP.NET MVC5 앱
public class ApplicationUser : IdentityUser
{
public DateTime BirthDate { get; set; }
}
지금 나는 것을 확인하는 단위 테스트를 만들려면 내 AccountController가 BirthDate를 올바르게 저장하고 있습니다.
나는 controller.Register 방법은 참조 용으로 여기를 포함하고있어 MVC5에 의해 생성 된 상용구 코드가 되나 TestUserStore
[TestMethod]
public void Register()
{
// Arrange
var userManager = new UserManager<ApplicationUser>(new TestUserStore<ApplicationUser>());
var controller = new AccountController(userManager);
// This will setup a fake HttpContext using Moq
controller.SetFakeControllerContext();
// Act
var result =
controller.Register(new RegisterViewModel
{
BirthDate = TestBirthDate,
UserName = TestUser,
Password = TestUserPassword,
ConfirmPassword = TestUserPassword
}).Result;
// Assert
Assert.IsNotNull(result);
var addedUser = userManager.FindByName(TestUser);
Assert.IsNotNull(addedUser);
Assert.AreEqual(TestBirthDate, addedUser.BirthDate);
}
라는 인 메모리 사용자 저장소를 만들었습니다.
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser() { UserName = model.UserName, BirthDate = model.BirthDate };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInAsync(user, isPersistent: false);
return RedirectToAction("Index", "Home");
}
else
{
AddErrors(result);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
내가 등록 (Register)을 호출하면 문제가 발생하는 SignInAsync가 호출됩니다. 최하층
private async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
}
은 상용구 코드는 토막
private IAuthenticationManager AuthenticationManager
{
get
{
return HttpContext.GetOwinContext().Authentication;
}
}
problm의 루트가 발생하는 곳이다를 포함한다. GetOwinContext에 대한이 호출은 내가 모의 할 수없는 확장 메소드이며 스텁으로 대체 할 수 없습니다 (물론 상용구 코드를 변경하지 않는 한). 나는이 테스트를 실행하면
은 내가 ASP.NET MVC 팀이 코드를 테스트 할 수 있도록하기 위해 매우 열심히 노력 예외를 이전 릴리스에서
Test method MVCLabMigration.Tests.Controllers.AccountControllerTest.Register threw exception:
System.AggregateException: One or more errors occurred. ---> System.NullReferenceException: Object reference not set to an instance of an object.
at System.Web.HttpContextBaseExtensions.GetOwinEnvironment(HttpContextBase context)
at System.Web.HttpContextBaseExtensions.GetOwinContext(HttpContextBase context)
at MVCLabMigration.Controllers.AccountController.get_AuthenticationManager() in AccountController.cs: line 330
at MVCLabMigration.Controllers.AccountController.<SignInAsync>d__40.MoveNext() in AccountController.cs: line 336
를 얻을. 이제는 AccountController를 테스트하는 것이 쉽지 않을 것 같습니다. 나는 몇 가지 선택권이있다. 이 확장 메서드를 호출하고 그 수준에서이 문제를
설정 테스트 목적으로 OWin 파이프 라인을 처리하지 않도록
나는
보일러 플레이트 코드를 수정할 수 있습니다
AuthN/AuthZ 인프라가 필요한 테스트 코드 작성을 피하십시오 (적절한 옵션이 아님)
어떤 도로가 더 좋은지 잘 모르겠습니다. 어느 쪽이든이 문제를 해결할 수 있습니다. 제 질문은 가장 좋은 전략입니다.
참고 : 예, 필자가 작성하지 않은 코드를 테스트 할 필요가 없음을 알고 있습니다. 제공된 UserManager 인프라 MVC5는 인프라 스트럭처입니다.하지만 ApplicationManager에 대한 수정 사항을 확인하는 테스트를 작성하거나 사용자 역할에 따라 동작을 확인하는 코드를 작성하려면 UserManager를 사용하여 테스트해야합니다.
안녕하세요. 당신이 언급 한 튜토리얼을 가르쳐주세요. 또한 Register 메소드 구현으로 질문을 업데이트 할 수 있다면 도움이 될 것입니다. – Spock
유닛 테스트에서 참조 할 때 HttpContext는 null이됩니다. 사용하는 속성 값을 반환하려면 모의 HttpContext 객체를 삽입해야 할 수도 있습니다. –
모의 설정을했는데 위의 샘플 코드가 아니었지만 지금 추가했습니다. –