Forms Authentication with business logic and unit testing
My business class has a method "Save" that when it is called it should automatically set MyObject.AspNetUserId (a guid property) to Membership.GetUser().ProviderUserKey then actually perform the save. I wrote the code but I am having an issue unit testing this.
In my unit test I have a line "FormsAuthentication.SetAuthCookie" that the test is breaking on. I'm assuming that is because my unit test is not being run within an HTTP context so it can't actually set the cookie.
Is there a way to get this to work or do I just have to manually test it on the demo site?
Is this a really bad practice and I should be doing something else? The goal of this code is to have the "CreatedBy" and "EditedBy" properties of my object set themselves automatical开发者_C百科ly so the programmer doesn't have to remember to every time in the website code. If anybody has a better method I'm open to ideas.
What about programming all authorization calls against an authorization interface? That way you can allow its implementation to be substituted during unit tests and set up expectations that the login method is called.
Here is an example:
public interface IAuthorization
{
bool ValidateUser(LoginUser u, string password);
LoginUser GetCurrentUser();
void LogIn(LoginUser user);
void LogOut();
IIdentity GetCurrentUserIdentity();
}
精彩评论