0

I have got following code and I have no clue which proper Unit Test I have write out for those methods and how it can be done. Basically I would like to use NUnit.Framework.

Thank you in advance for ANY clue!

   [AllowAnonymous]
        public ActionResult ForgotPassword(string id)
        {
            var model = new ForgotPasswordViewModel();

            if (!string.IsNullOrEmpty(id))
            {
                #region Process Reset Password Key

                try
                {
                    var forgotPasswordEvent = AppModel.ForgotPasswordEvents.SingleOrDefault(x => x.UIDHash == id);

                    if (forgotPasswordEvent != null)
                    {
                        var stringToHash = string.Format("{0}---{1}---{2}", forgotPasswordEvent.UID.ToString(),
                                    forgotPasswordEvent.UserId.ToString(), forgotPasswordEvent.Created.ToString());

                        var readyHash = SecurityHelper.GetHashString(stringToHash);

                        if (id == readyHash)
                        {
                            var forgotPasswordEventUserId = forgotPasswordEvent.UserId.ToString();
                            var realUser = AppModel.AspNetUsers.SingleOrDefault(x => x.Id == forgotPasswordEventUserId);

                            if (realUser != null)
                            {
                                var resetPasswordViewModel = new ResetPasswordViewModel();
                                resetPasswordViewModel.ResetPasswordData = id;
                                resetPasswordViewModel.UserName = realUser.UserName;

                                return RedirectToAction("ResetPassword", "Account", resetPasswordViewModel); // ResetPassword(resetPasswordViewModel);
                            }

                        }
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                catch (Exception)
                {
                }

                #endregion
            }

            #region Check if the user is logged in and fill out fileds for him.

            var sessionManager = SessionWrapper.GetFromSession<SessionManager>("_SessionManager");

            if (sessionManager != null)
            {
                var clientId = sessionManager.AppUser.ClientId;

                if (clientId != null)
                {
                    model.Email = sessionManager.AppUser.EmailID;
                    model.UserName = sessionManager.AppUser.UserName;
                    model.IsLoggedInUser = true;
                }
            }

            #endregion

            return View(model);
        }

        [HttpPost]
        [AllowAnonymous]
        public ActionResult ForgotPassword(ForgotPasswordViewModel model, FormCollection formCollection)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    #region Check user input

                    var user = AppModel.AspNetUsers.SingleOrDefault(x => x.UserName == model.UserName);

                    var areErrors = false;

                    if (user == null)
                    {
                        ModelState.AddModelError("UserDoesnotExist", DLMModelEntities.Properties.Resource.UserDoesNotExist);
                        areErrors = true;
                    }

                    if (user.EmailID != model.Email)
                    {
                        ModelState.AddModelError("EmailIsWrong", DLMModelEntities.Properties.Resource.EmailIsWrong);
                        areErrors = true;
                    }

                    if (areErrors)
                        return View(model);

                    #endregion

                    #region Send Email and inform user

                    try
                    {
                        var forgotPasswordEvent = new ForgotPasswordEvent();

                        var resetPasswordEmailUserState = new ResetPasswordEmailUserState();
                        resetPasswordEmailUserState.ForgotPasswordEventId = Guid.NewGuid();
                        resetPasswordEmailUserState.UserId = Guid.Parse(user.Id);
                        resetPasswordEmailUserState.Created = DateTime.Now;

                        forgotPasswordEvent.UID = resetPasswordEmailUserState.ForgotPasswordEventId;
                        forgotPasswordEvent.UserId = resetPasswordEmailUserState.UserId;
                        forgotPasswordEvent.IsSent = false;
                        forgotPasswordEvent.Created = resetPasswordEmailUserState.Created;

                        var stringToHash = string.Format("{0}---{1}---{2}", resetPasswordEmailUserState.ForgotPasswordEventId.ToString(),
                             resetPasswordEmailUserState.UserId.ToString(), resetPasswordEmailUserState.Created.ToString());

                        forgotPasswordEvent.UIDHash = SecurityHelper.GetHashString(stringToHash);

                        AppModel.ForgotPasswordEvents.Add(forgotPasswordEvent);
                        AppModel.SaveChanges();

                        var smtp = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");

                        // Set the MailerModel properties that will be passed to the MvcMailer object.
                        var m = new MailerModel();
                        m.UserName = user.UserName;
                        m.ResetPasswordLink = string.Format("{0}/{1}", Request.Url.AbsoluteUri, forgotPasswordEvent.UIDHash);
                        m.FromEmail = smtp.From;
                        m.Subject = AppConfiguration.ResetEmailSubject;
                        m.ToEmail = model.Email;                     

                        var client = new SmtpClientWrapper();

                        client.SendCompleted += (sender, e) =>
                        {
                            if (e.Error != null || e.Cancelled)
                            {
                                // Handle Error                                
                            }
                            else
                            {
                                try
                                {
                                    var forgotPasswordEventsToUpdate = AppModel.ForgotPasswordEvents.SingleOrDefault(x => x.UID == resetPasswordEmailUserState.ForgotPasswordEventId);

                                    if (forgotPasswordEventsToUpdate != null)
                                    {
                                        forgotPasswordEventsToUpdate.IsSent = true;
                                        AppModel.SaveChanges();
                                    }
                                }
                                catch (Exception ex)
                                {                                    
                                    ModelState.AddModelError("EmailEx", ex.Message);
                                }
                            }
                        };

                        Mailer.PasswordReset(m).SendAsync(resetPasswordEmailUserState, client);

                        model.IsResetEMailSent = true;
                    }
                    catch (Exception ex)
                    {
                        ModelState.AddModelError("EmailEx", ex.Message);
                    }

                    #endregion
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("EmailEx", ex.Message);
                }
            }

            return View(model);
        }
1
  • 1
    Try Test-Driven Development... Commented Mar 25, 2014 at 18:08

1 Answer 1

2

As your code looks ltl messed up with more than one responsibility.

For Starter what you can do here is:

  1. Refactor your code into small code snippets and move those dependencies into another classes.
  2. when you will be done with first step you will be able to mock those classes using MOQ or NMock or another framework.

Let me know if you have any doubt in above points.

Sign up to request clarification or add additional context in comments.

1 Comment

I have used MOQ and I think it is good for MVC kind of framework.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.