0

I'm trying to test my ASP.NET MVC4 Application within Visual Studio and I am running into problems when testing WebSecurity.Login(). It seems to work perfectly when running my application but throws out an error when testing.

Method to test:

[HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Login(HomeModels.LoginModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var username = model.Username;
                    var password = model.Password;

                    if (WebSecurity.Login(username, password, true))
                    {

                        if (Roles.Provider.IsUserInRole(username, "admin"))
                        {
                            return RedirectToAction("AdminHome");
                        }
                        else if (Roles.Provider.IsUserInRole(username, "user"))
                        {
                            return RedirectToAction("LoginSuccessful");
                        }

                    }
                    else
                    {
                        //String errorMessage = "Login was not successful.";
                    }
                }
                catch (MemberAccessException e)
                {
                    ModelState.AddModelError("", e);
                }
            }
            return View(model);
        }

Test Method:

[TestMethod]
        public void TestLoginAdminSuccessfulView()
        {
            HomeController controller = new HomeController();
            Ecommerce.Models.HomeModels.LoginModel login = new Ecommerce.Models.HomeModels.LoginModel();
            login.Username = "sgupta";
            login.Password = "sgupta2189";
            var result = (RedirectToRouteResult) controller.Login(login);
            Assert.AreEqual("AdminHome", result.RouteName);
        }

Error Message:

Test method EcommerceUnitTests.Controllers.HomeControllerTest.TestLoginAdminSuccessfulView threw exception: 
System.InvalidOperationException: To call this method, the "Membership.Provider" property must be an instance of "ExtendedMembershipProvider".

Error Stack Trace:

WebMatrix.WebData.WebSecurity.VerifyProvider()
WebMatrix.WebData.WebSecurity.Login(String userName, String password, Boolean persistCookie)
Ecommerce.Controllers.HomeController.Login(LoginModel model)
EcommerceUnitTests.Controllers.HomeControllerTest.TestLoginAdminSuccessfulView() 
4

2 回答 2

1

copy the working web.config to app.config in the project containing your tests. Make sure your Test project references assembly that is / contains your custom member provider. If the main project is working, check what references it has.

于 2013-01-30T10:21:23.793 回答
-1

I ended up restructuring it all and using ASP.NET's default membership provider.

于 2013-02-14T12:17:05.993 回答