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