I using ASP.NET Identity and when a user want to register get this error:
Value cannot be null.\r\nParameter name: manager.
Here is my Register Action code:
public virtual ActionResult Register(string nm, string em, string ps)
{
var redirectUrlPanel = new UrlHelper(Request.RequestContext).Action("Index", "HomeUsers", new { area = "Users" });
var redirectUrlAuction = new UrlHelper(Request.RequestContext).Action("Auction", "Default", new { area = "" });
if (ModelState.IsValid)
{
try
{
var user = new Q_Users();
user.UserName = nm;
user.Email = em;
user.SecurityStamp = Guid.NewGuid().ToString();
var adminresult = UserManager.Create(user, ps);
//Add User Admin to Role Admin
if (adminresult.Succeeded)
{
//Find Role Admin
var role = RoleManager.FindByName("Admin");
var result = UserManager.AddToRole(user.Id, role.Name);
if (result.Succeeded)
{
return Json(new { OK = "1", UrlPanel = redirectUrlPanel, UrlAuction = redirectUrlAuction });
}
}
else
{
return Json(new { OK = "0", UrlPanel = redirectUrlPanel, UrlAuction = redirectUrlAuction });
}
}
catch (Exception ex) { }
return Json(new { OK = "0", UrlPanel = redirectUrlPanel, UrlAuction = redirectUrlAuction });
}
else
{
return Json(new { OK = "0", UrlPanel = redirectUrlPanel, UrlAuction = redirectUrlAuction });
}
}
And the error in this Line: var adminresult = UserManager.Create(user, ps);
You are getting the error because the role manager was not initialized
To resolve this, follow the steps below
In the IdentityModels.cs file of the Models folder, Add the class below to the Models namespace.
public class ApplicationRole : IdentityRole
{
public ApplicationRole() : base() { }
public ApplicationRole(string name) : base(name) { }
}
In you IdentityConfig.cs file in App_Start folder, Add the class below
public class ApplicationRoleManager : RoleManager<ApplicationRole>
{
public ApplicationRoleManager(IRoleStore<ApplicationRole, string> roleStore)
: base(roleStore)
{
}
public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
{
return new ApplicationRoleManager(new RoleStore<ApplicationRole>(context.Get<ApplicationDbContext>()));
}
}
Go to Startup.Auth.cs file in the App_Start folder and add the code below to the ConfigureAuth Method.
app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
You should stop getting the errors after this.
Hope this helps.
Related
I created a sample ASP.NET MVC application.The default application provided by the Visual Studio.
I created folder named Utilities and place the below 4 classes
Connection
ConnectionRepository
SecurityManager
SessionManger
Below are the code of the above classes
public class Connection
{
public string ConnectionString { get; set; }
public Connection(string connectionStr)
{
this.ConnectionString = connectionStr;
}
public User GetUser(string userId)
{
return new User() { UserId="User1",Email="User1#company.com" };
}
}
******
using LegacyHttpContext = System.Web.HttpContext;
namespace SampleNunitApplication.Utilities
{
public class ConnectionRepository
{
public Connection ConnectionData
{
get
{
Connection con;
if(Convert.ToBoolean(LegacyHttpContext.Current.Application["isSourceOffline"].ToString()))
{
con = this.RefreshConfigDataFromAppServer();
}
else
{
con = this.RefreshConfigDataFromDB();
}
return con;
}
}
public Connection RefreshConfigDataFromDB()
{
Connection dbConnection = new Utilities.Connection("DataFromSqlServer");
LegacyHttpContext.Current.Application["_connData"] = dbConnection;
return dbConnection;
}
public Connection RefreshConfigDataFromAppServer()
{
Connection appConnection = new Utilities.Connection("DataFromAppServer");
LegacyHttpContext.Current.Application["_connData"] = appConnection;
return appConnection;
}
}
}
*******
using LegacyHttpContext = System.Web.HttpContext;
namespace SampleNunitApplication.Utilities
{
public class SecurityManager
{
public static SecurityManager GetFromCache()
{
if(LegacyHttpContext.Current.Application["SecurityManager"]==null)
{
SecurityManager securityManager = new SecurityManager();
LegacyHttpContext.Current.Application["SecurityManager"] = securityManager;
return securityManager;
}
else
{
return LegacyHttpContext.Current.Application["SecurityManager"] as SecurityManager;
}
}
public User GetAuthenticatedUser(string userId)
{
ConnectionRepository connRepository = new ConnectionRepository();
Connection con = connRepository.ConnectionData;
return con.GetUser(userId);
}
}
}
*****
public class SessionManager
{
public string EmployeeId { get; set; }
public string Email { get; set; }
public static void SaveToSessionState(HttpSessionStateBase state,SessionManager sessionManager)
{
state["SessionManager"] = sessionManager;
}
public static SessionManager LoadFromSessionState(HttpSessionStateBase state)
{
if (state["SessionManager"] ==null)
{
return new SessionManager();
}
return state["SessionManager"] as SessionManager;
}
}
****In the HomeController.cs***
public ActionResult Index()
{
SessionManager authenticateUser = SessionManager.LoadFromSessionState(this.HttpContext.Session);
ValidationModel.Validate(authenticateUser.EmployeeId, this.HttpContext);
SessionManager.LoadFromSessionState(this.HttpContext.Session);
return View();
}
*******************In the Global.asax***
protected void Session_Start()
{
HttpSessionStateWrapper sessionWrapper = new HttpSessionStateWrapper(System.Web.HttpContext.Current.Session);
System.Web.HttpContext.Current.Application["isSourceOffline"] = false;
SessionManager authenticateUser = SessionManager.LoadFromSessionState(sessionWrapper);
User user = SecurityManager.GetFromCache().GetAuthenticatedUser("User1");
authenticateUser.EmployeeId = user.UserId;
authenticateUser.Email = user.Email;
SessionManager.SaveToSessionState(sessionWrapper, authenticateUser);
}
******
I created a class library project and created below mock code
[TestClass] public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
var application = new Mock<HttpApplicationStateBase>();
SecurityManager securityManager = new SecurityManager();
application.SetupGet(s => s["isSourceOffline"]).Returns(true);
application.SetupGet(s => s["SecurityManager"]).Returns(securityManager);
var context = new Mock<HttpContextBase>();
var request = new Mock<HttpRequestBase>();
var response = new Mock<HttpResponseBase>();
var session = new Mock<HttpSessionStateBase>();
var server = new Mock<HttpServerUtilityBase>();
session.Setup(s => s.SessionID).Returns(Guid.NewGuid().ToString());
context.Setup(c => c.Request).Returns(request.Object);
context.Setup(c => c.Response).Returns(response.Object);
context.Setup(c => c.Session).Returns(session.Object);
context.Setup(c => c.Application).Returns(application.Object);
context.Setup(c => c.Server).Returns(server.Object);
SessionManager authenticatedUser = new SessionManager();
authenticatedUser.EmployeeId = "TestUser";
authenticatedUser.Email = "Test#testmail.com";
SessionManager.SaveToSessionState(context.Object.Session, authenticatedUser);
HomeController objController = new HomeController();
objController.ControllerContext = new System.Web.Mvc.ControllerContext(context.Object, new RouteData(), objController);
objController.Index();
}
}
If I run the ASP.NET MVC application it works good. But when i run the test case it hits the Index method of the HomeController but SessionManager authenticateUser = SessionManager.LoadFromSessionState(this.HttpContext.Session); is not populating from the session. Properties in the authenticateUser are null.
Seems like mock session is not working please help
i need to when user regiter add in tabel AspNetRole add user id and role id .
but when i create a user show me this error .
how can i insert role in database ?
/*************************************************************************************************/
identityconfig :
public class ApplicationRoleManager : RoleManager<IdentityRole>
{
public ApplicationRoleManager(IRoleStore<IdentityRole, string> roleStore)
: base(roleStore)
{
}
public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
{
return new ApplicationRoleManager(new RoleStore<IdentityRole>(context.Get<ApplicationDbContext>()));
}
}
public static class SecurityRole
{
public const string Admin = "admin";
public const string Accounting = "accounting";
}
StartupAuth :
app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
AccountController :
public ApplicationRoleManager RoleManager
{
get
{
return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
}
private set
{
_roleManager = value;
}
}
public async Task<ActionResult> Register(RegisterViewModel model, HttpPostedFileBase IamgeProfile)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Username, Email = model.Email };
user.Name = model.Name;
user.Family = model.Family;
user.Address = model.Address;
user.BankName = model.BankName;
user.City = model.City;
user.Ostan = model.Ostan;
user.PhoneNumber = model.PhoneNumber;
user.HomeNumber = model.HomeNumber;
user.ShabaNo = model.ShabaNo;
user.PostaCode = model.PostaCode;
user.NationalCode = model.NationalCode;
if (IamgeProfile != null)
{
IamgeProfile = Request.Files[0];
var ext = System.IO.Path.GetExtension(IamgeProfile.FileName);
if (ext == ".jpeg" || ext == ".jpg" || ext == ".png")
{
string filename = model.Name + model.Family + model.NationalCode + ext;
IamgeProfile.SaveAs(Server.MapPath(#"~/Images/UserImageProfile/" + filename));
user.IamgeProfile = filename;
}
}
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
await UserManager.AddToRoleAsync(user.Id, role: SecurityRole.Accounting);
var code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking this link: link");
ViewBag.Link = callbackUrl;
return View("DisplayEmail");
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
To add a role into AspNetRoles you can do this in your Seed() or other startup method:
if (!context.Roles.Any(r => r.Name == "Admin"))
{
var store = new RoleStore<IdentityRole>(context);
var manager = new RoleManager<IdentityRole>(store);
var role = new IdentityRole { Name = "Admin" };
manager.Create(role);
}
https://msdn.microsoft.com/en-us/library/dn613057(v=vs.108).aspx
I am trying to write a Unit test of index method of my ClientController.
Here is my ClientController:
public ClientController(ApplicationUserManager clientManager, ApplicationRoleManager roleManager)
{
ClientManager = clientManager;
RoleManager = roleManager;
}
private ApplicationRoleManager _roleManager;
public ApplicationRoleManager RoleManager
{
get
{
return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
}
set
{
_roleManager = value;
}
}
private ApplicationUserManager _clientManager;
public ApplicationUserManager ClientManager
{
get
{
return _clientManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
set
{
_clientManager = value;
}
}
public async Task<ActionResult> Index(string filter, string error, string searchName, int? page, int? records)
{
List<string> filterCriteria = new List<string>();
filterCriteria.Add("Choose Email");
var listClients = new List<ApplicationUser>();
// Get the list of clients ( users with client role )
foreach (var user in ClientManager.Users.Where(u => u.IsActive == true && (u.FirstNames.Contains(searchName) || u.LastName.Contains(searchName)
|| searchName == null)).OrderBy(u => u.FirstNames).ToList())
{
if (await ClientManager.IsInRoleAsync(user.Id, "Client"))
{
listClients.Add(user);
filterCriteria.Add(user.Email);
}
}
ViewBag.emails = new SelectList(filterCriteria);
ViewBag.error = error;
if (filter == null || filter.Equals("Choose Email"))
{
return View(listClients.ToList().ToPagedList(page ?? 1, records ?? 15));
}
else
{
return View();
}
And here is my attempt to write a unit test of it.
[TestMethod]
public void Index_Get_RetrievesAllClientFromRepository()
{
// Arrange,
ApplicationUser Client1 = GetClientNamed("1", 1, 1, DateTime.Now, "Abc", "Abc", "Xyz", "343433443", "abc#xyz.com", "M", "06091980-ABSD");
var userStore = new Mock<IUserStore<ApplicationUser>>();
var userManager = new UserManager<ApplicationUser>(userStore.Object);
userStore.Setup(x => x.CreateAsync(Client1))
.Returns(Task.FromResult(IdentityResult.Success));
userStore.Setup(x => x.FindByNameAsync(Client1.UserName))
.Returns(Task.FromResult(Client1));
var roleStore = new Mock<IRoleStore<IdentityRole>>();
var roleManager = new Mock<ApplicationRoleManager>(roleStore.Object);
var controller = new ClientController(
userStore.Object as ApplicationUserManager, roleManager.Object);
// Act
var resultTask = controller.Index("Choose Email", "", "", 1, 15);
resultTask.Wait();
var result = resultTask.Result;
var model = (List<ApplicationUser>)((ViewResult)result).Model;
CollectionAssert.Contains(model, Client1);
}
userStore.Object always come null. I am quite newbie in unit testing and I have looked for many solution but there isn't such use case. Any help would be appreciated.
userStore.Object is coming as null because of the as cast, which returns null if the conversion isn't possible.
userStore is defined as:
new Mock<IUserStore<ApplicationUser>>();
which means that .Object will be of type IUserStore<ApplicationUser>,
which isn't an ApplicationUserManager, so you end up with null.
I have a need to override authorize attribute.
Basically if its an ajax request and the user is not logged in or is not in specified roles then i want to return a JSON. The JSON will tell the caller the reason as not logged in or not in role and needs to return the redirect to url. In case of not signed it, it also needs to give back ReturnUrl.
If its not an ajax request then i want the default processing by Authorize attribute to kick in.
We are using forms authentication and the sign in url and error pages are specified in the web.config file.
Following is my take at it but i am not getting the following right
missing roles processing in case of an ajax request
in case of not an ajax request (else block), i am redirecting the user to the sign in page. i want the default autorize attribute to kickin in this case
I just need the push in the right direction... tutorial or a blog pointer is all i need to learn and accomplish this....
public class AuthorizePartnerProgramsAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
HttpContext httpContext = HttpContext.Current;
var url = new UrlHelper(filterContext.RequestContext);
var request = filterContext.HttpContext.Request;
if (request.IsAuthenticated == false)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
if (request.Url != null)
filterContext.Result = CommonUtilities.AddJsonUtf8Encoding(new JsonResult { Data = new { error = true, singinerror = true, message = "Sign in required!", returnUrl = request.UrlReferrer.AbsolutePath.ToString() } });
else
filterContext.Result = CommonUtilities.AddJsonUtf8Encoding(new JsonResult { Data = new { error = true, singinerror = true, message = "Sign in required!" } });
}
else
{
if (request.UrlReferrer != null)
{
filterContext.Result = new RedirectResult(url.Action("Index", "SignIn", new { Area = "Account", ReturnUrl = filterContext.RequestContext.HttpContext.Request.UrlReferrer.AbsolutePath.ToString() }));
}
else
{
filterContext.Result = new RedirectResult(url.Action("Index", "SignIn", new { Area = "Account"}));
}
}
}
}
}
Here is my second stab at it. I think i am now more confused than before and need help setting it up properly
public class AuthorizeCustomAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
var request = filterContext.RequestContext.HttpContext.Request;
if (request.IsAjaxRequest())
{
var url = new UrlHelper(filterContext.RequestContext);
var urlReferer = request.UrlReferrer != null
? request.UrlReferrer.ToString()
: String.Empty;
var signInUrl = url.Action("Index", "SignIn", new { Area = "Account", ReturnUrl = urlReferer });
var accessDeniedUrl = url.Action("PageAccessDenied", "Error", new { Area = "" });
if (!request.IsAuthenticated)
{
//not authenticated
filterContext.Result =
CommonUtilities.AddJsonUtf8Encoding(new JsonResult
{
Data =
new {error = true, singinerror = true, message = "Sign in required!", url = signInUrl},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
});
}
}
else
{
base.HandleUnauthorizedRequest(filterContext);
}
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (httpContext.Request.IsAjaxRequest())
{
//Use [AuthorizeCustom(Roles="MyRole1,MyRole2")]
//or [AuthorizeCustom]
//roles may not have been applied here
//checking authentication will be done by the HandleUnauthorizedRequest?????
//if no roles are specified then it is true = so give access to the resource
//user may have multiple roles or single role assigned, check and if not in role then return json back.
//....
}
else
{
return base.AuthorizeCore(httpContext);
}
}
}
This helped me setting up mine
http://www.dotnet-tricks.com/Tutorial/mvc/G54G220114-Custom-Authentication-and-Authorization-in-ASP.NET-MVC.html
use
[AuthorizeCustom(Roles = RoleNames.Admin)]
Here is the full working attribute for me without any cleanup.
public class AuthorizeCustomAttribute : AuthorizeAttribute
{
#region CONSTANTS
public const string SectionStemFuture = "StemFuture";
#endregion
#region PROPERTIES
private string Section { get; set; }
#endregion
#region Constructor
public AuthorizeCustomAttribute()
{
Section = String.Empty;
}
public AuthorizeCustomAttribute(string section)
{
Section = section;
}
#endregion
#region Overrides
public override void OnAuthorization(AuthorizationContext filterContext)
{
var request = filterContext.HttpContext.Request;
var url = new UrlHelper(filterContext.RequestContext);
/*
var urlReferer = request.UrlReferrer != null
? request.UrlReferrer.ToString()
: String.Empty;
*/
var urlReferer = request.Url.PathAndQuery;
var signInUrl = url.Action("Index", "SignIn", new { Area = "Account", ReturnUrl = urlReferer });
var accessDeniedUrl = url.Action("PageAccessDenied", "Error", new { Area = "" });
//overwrite the default sign in URL according to the section
if (!String.IsNullOrWhiteSpace(Section))
{
switch (Section)
{
case SectionStemFuture:
signInUrl = url.Action("Index", "StemFutureHome", new { Area = "StemFuture", ReturnUrl = urlReferer });
break;
}
}
if (!request.IsAuthenticated)
{
//not authenticated
if (request.IsAjaxRequest())
{
filterContext.Result =
CommonUtilities.AddJsonUtf8Encoding(new JsonResult
{
Data =
new {error = true, signinerror = true, message = "Sign in required", url = signInUrl},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
});
}
else
{
//this is not an ajax request
if (!String.IsNullOrWhiteSpace(Section))
{
filterContext.Result = new RedirectResult(signInUrl);
}
else
{
//let the base authorization take care of it
base.OnAuthorization(filterContext);
}
}
}
else if (!String.IsNullOrWhiteSpace(base.Roles))
{
var isRoleError = true;
var rolesAllowed = base.Roles.Split(',');
//authenticated and we have some roles to check against
var user = filterContext.HttpContext.User;
if (user != null && rolesAllowed.Any())
{
foreach (var role in rolesAllowed)
{
if (user.IsInRole(role))
{
isRoleError = false;
}
}
}
if (isRoleError)
{
if (request.IsAjaxRequest())
{
filterContext.Result =
CommonUtilities.AddJsonUtf8Encoding(new JsonResult
{
Data =
new
{
error = true,
signinerror = true,
message = "Access denied",
url = accessDeniedUrl
},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
});
}
else
{
//here we will need to pass to the access denied
filterContext.Result = new RedirectResult(accessDeniedUrl);
}
}
}
}
#endregion
}
Trying to figure out how to adequately test my accounts controller. I am having problem testing the successful logon scenario.
Issue 1) Am I missing any other tests.(I am testing the model validation attributes separately)
Issue 2) Put_ReturnsOverviewRedirectToRouteResultIfLogonSuccessAndNoReturnUrlGiven() and Put_ReturnsRedirectResultIfLogonSuccessAndReturnUrlGiven() test are not passing. I have narrowed it down to the line where i am calling _membership.validateuser(). Even though during my mock setup of the service i am stating that i want to return true whenever validateuser is called, the method call returns false.
Here is what I have gotten so far
AccountController.cs
[HandleError]
public class AccountController : Controller
{
private IMembershipService _membershipService;
public AccountController()
: this(null)
{
}
public AccountController(IMembershipService membershipService)
{
_membershipService = membershipService ?? new AccountMembershipService();
}
[HttpGet]
public ActionResult LogOn()
{
return View();
}
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (_membershipService.ValidateUser(model.UserName,model.Password))
{
if (!String.IsNullOrEmpty(returnUrl))
{
return Redirect(returnUrl);
}
return RedirectToAction("Index", "Overview");
}
ModelState.AddModelError("*", "The user name or password provided is incorrect.");
}
return View(model);
}
}
AccountServices.cs
public interface IMembershipService
{
bool ValidateUser(string userName, string password);
}
public class AccountMembershipService : IMembershipService
{
public bool ValidateUser(string userName, string password)
{
throw new System.NotImplementedException();
}
}
AccountControllerFacts.cs
public class AccountControllerFacts
{
public static AccountController GetAccountControllerForLogonSuccess()
{
var membershipServiceStub = MockRepository.GenerateStub<IMembershipService>();
var controller = new AccountController(membershipServiceStub);
membershipServiceStub
.Stub(x => x.ValidateUser("someuser", "somepass"))
.Return(true);
return controller;
}
public static AccountController GetAccountControllerForLogonFailure()
{
var membershipServiceStub = MockRepository.GenerateStub<IMembershipService>();
var controller = new AccountController(membershipServiceStub);
membershipServiceStub
.Stub(x => x.ValidateUser("someuser", "somepass"))
.Return(false);
return controller;
}
public class LogOn
{
[Fact]
public void Get_ReturnsViewResultWithDefaultViewName()
{
// Arrange
var controller = GetAccountControllerForLogonSuccess();
// Act
var result = controller.LogOn();
// Assert
Assert.IsType<ViewResult>(result);
Assert.Empty(((ViewResult)result).ViewName);
}
[Fact]
public void Put_ReturnsOverviewRedirectToRouteResultIfLogonSuccessAndNoReturnUrlGiven()
{
// Arrange
var controller = GetAccountControllerForLogonSuccess();
var user = new LogOnModel();
// Act
var result = controller.LogOn(user, null);
var redirectresult = (RedirectToRouteResult) result;
// Assert
Assert.IsType<RedirectToRouteResult>(result);
Assert.Equal("Overview", redirectresult.RouteValues["controller"]);
Assert.Equal("Index", redirectresult.RouteValues["action"]);
}
[Fact]
public void Put_ReturnsRedirectResultIfLogonSuccessAndReturnUrlGiven()
{
// Arrange
var controller = GetAccountControllerForLogonSuccess();
var user = new LogOnModel();
// Act
var result = controller.LogOn(user, "someurl");
var redirectResult = (RedirectResult) result;
// Assert
Assert.IsType<RedirectResult>(result);
Assert.Equal("someurl", redirectResult.Url);
}
[Fact]
public void Put_ReturnsViewIfInvalidModelState()
{
// Arrange
var controller = GetAccountControllerForLogonFailure();
var user = new LogOnModel();
controller.ModelState.AddModelError("*","Invalid model state.");
// Act
var result = controller.LogOn(user, "someurl");
var viewResult = (ViewResult) result;
// Assert
Assert.IsType<ViewResult>(result);
Assert.Empty(viewResult.ViewName);
Assert.Same(user,viewResult.ViewData.Model);
}
[Fact]
public void Put_ReturnsViewIfLogonFailed()
{
// Arrange
var controller = GetAccountControllerForLogonFailure();
var user = new LogOnModel();
// Act
var result = controller.LogOn(user, "someurl");
var viewResult = (ViewResult) result;
// Assert
Assert.IsType<ViewResult>(result);
Assert.Empty(viewResult.ViewName);
Assert.Same(user,viewResult.ViewData.Model);
Assert.Equal(false,viewResult.ViewData.ModelState.IsValid);
}
}
}
Figured out how to fix my tests.
[Fact]
public void Put_ReturnsRedirectToRouteResultForOverviewIfLogonSuccessAndNoReturnUrlGiven()
{
// Arrange
var mocks = new MockRepository();
var mockMembershipService = mocks.StrictMock<IMembershipService>();
using (mocks.Record())
{
Expect.Call(mockMembershipService.ValidateUser("", "")).IgnoreArguments().Return(true).Repeat.Any();
}
var controller = new AccountController(mockMembershipService);
var user = new LogOnModel();
// Act
ActionResult result;
using (mocks.Playback()){
result = controller.LogOn(user, null);
}
// Assert
Assert.IsType<RedirectToRouteResult>(result);
var redirectresult = (RedirectToRouteResult)result;
Assert.Equal("Overview", redirectresult.RouteValues["controller"]);
Assert.Equal("Index", redirectresult.RouteValues["action"]);
}