0
我對單元測試非常陌生,所以我現在開始進行第一套測試。我正在使用Telerik的Library JustMock
。儘管任何單元測試信息都很好。我在通過我的方法接口服務時遇到了一些問題。下面是我MembershipController.Register(model)
方法...第一單元測試! ASP.NET MVC與知識庫導致錯誤
[CaptchaValidator]
[HttpPost]
public ActionResult Register(Models.Membership.Registration model)
{
// just for good mesure, truncate any spaces that are given
System.Text.RegularExpressions.Regex.Replace(model.Email, @"\s", "");
if (ModelState.IsValid)
{
// Attempt to register the User and return any applicable status that has to do
// with the result.
var createStatus = membershipService.RegisterMember(model.Email, model.Password);
// if the member is able to be created successfully, log them in now and begin the
// authentication portion of the registration, otherwise, display the registration
// errors and return to the view.
if (createStatus == Membership.MemberCreateStatus.Success)
{
formsAuthentication.SignIn(model.Email, false /* createPersistentCookie */);
return RedirectToAction("Success");
}
else
{
ModelState.AddModelError("", Membership.Validator.ErrorCodeToString(createStatus));
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
這裏是微不足道的測試我試圖運行...因爲membershipService
被解析爲空
[TestMethod]
public void Register_Post_ReturnsRedirectOnSuccess()
{
// Arrange
var controller = Mock.Create<Web.Controllers.MembershipController>();
var repository = Mock.Create<Membership.IMembershipService>();
Mock.Arrange(() => repository.RegisterMember("[email protected]", "acceptiblePassword")).Returns(Membership.MemberCreateStatus.Success);
// Model
var model = new Web.Models.Membership.Registration
{
Email = "[email protected]",
Password = "acceptiblePassword",
ConfirmPassword = "acceptiblePassword"
};
// Act
var result = controller.Register(model);
// Assert
Assert.IsInstanceOfType(result, typeof(RedirectToRouteResult));
}
測試失敗。我不知道這裏要做什麼。這是我第一次在ASP.NET MVC的單元測試方面進行了嘗試。任何人都可以給我一些建議嗎?
我使用Ninject
通過構造函數注入IMembershipService
。它由MembershipService
類執行。我運行代碼時運行良好,但單元測試失敗。
我沒有看到你傳遞`repository`到你的控制器的任何地方。通常情況下,你可以在你的控制器的構造函數中使用`IMembershipService`作爲參數,然後你可以在需要時傳入,或者使用MVC的服務定位器獲取Ninject實例並將其傳入。 – Buildstarted 2011-02-18 18:40:39