我正在学习用于单元测试的 Moles 框架。我有一个带有 AccountController 的模板 ASP MVC 项目,我想测试的方法是 Register()
[HttpPost]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
MembershipCreateStatus createStatus;
Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, false, null, out createStatus);
if (createStatus == MembershipCreateStatus.Success)
{
string confirmationGuid = Membership.GetUser(model.UserName).ProviderUserKey.ToString();
string confirmUrl = System.Web.HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) +
"/account/confirm?id=" + confirmationGuid;
var message = new MailService.MessageModel
{
UserName = model.UserName,
MessageSubject = "Registration confirmation",
MessageBody = "Please follow the link below in order to activate your account:\n" + confirmUrl
};
MailService.SendConfrimationEmail(message);
return RedirectToAction("Confirmation", "Account");
}
else
{
ModelState.AddModelError("", ErrorCodeToString(createStatus));
}
}
return View(model);
}
它依赖于静态方法Membership.CreateUser
。测试方法如下所示:
[TestMethod()]
[HostType("Moles")]
public void RegisterTest()
{
using (MolesContext.Create())
{
var target = new AccountController();
var model = new RegisterModel
{
UserName = "TestUser1",
Password = "12345678",
ConfirmPassword = "12345678",
Email = "mail@mail.com"
};
target.Register(model);
var exists = Membership.GetUser("TestUser1") != null;
Assert.IsTrue(exists);
}
}
我希望 Moles 框架模拟方法内部的静态方法,Register
但是在调试时我发现它createStatus
总是InvalidAnswer
有价值,因此测试失败。如何在不手动创建任何接口或委托的情况下使用 Moles 框架来实现这一点?