1

我正在学习用于单元测试的 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 框架来实现这一点?

4

1 回答 1

1

我终于找到了一种模拟Membership.CreateUser方法的方法,尽管实现有点长。

MMembership.CreateUserStringStringStringStringStringBooleanObjectMembershipCreateStatusOut = 
   (string userName, string password, string email, string passwordQuestion, 
    string passwordAnswer, bool isApproved, object providerUserKey,
    out MembershipCreateStatus @createStatus) =>
{
    @createStatus = MembershipCreateStatus.Success;
    return null;
};
于 2012-07-17T01:22:31.873 回答