Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8264935
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 8, 20262026-06-08T04:37:44+00:00 2026-06-08T04:37:44+00:00

I’m trying to do some unit testing in MVC, however some of my functions

  • 0

I’m trying to do some unit testing in MVC, however some of my functions require a UserID to work (i.e. save to the database as a foreign key).

The UserID is stored in the UserData attribute of my FormsAuthenticationTicket how would I ‘fake’ a UserID at unit test time so that I can run unit testing with a fake user. Is this even possible?

I’m using the built in unit testing system from Microsoft.

The test code I’m planning on using is akin to

[TestMethod]
public void EnsureAddItemAddsItems()
{
   // Arrange
   ShoppingCartController controller = new ShoppingCartController();
   // These would be populated by dummy values
   Guid itemID = Guid.Empty;
   Guid itemTypeID = Guid.Empty;

   // Act
   ViewResult result = controller.AddItem(itemTypeID, itemID);

   //Assert
   Assert.AreEqual("Your shopping cart contains 1 item(s)",result.ViewBag.Message);
}

Some sample code might look like :-

public ActionResult AddItem(Guid itemType, Guid itemID, string returnAction)
{
    ShoppingCartViewModel oModel = new ShoppingCartViewModel();

    string szName = String.Empty;
    int price = 0;


    using (var context = new entityModel())
    {
        // This is the section I'm worries about
>>>>>>>>> Guid gUserID = this.GetCurrentUserID(); <<<<<<<<<

        var currentSession = this.CreateOrContinueCurrentCartSession(gUserID);

        var oItem = new ShoppingCartItem();
        oItem.Id = Guid.NewGuid();
        oItem.ItemId = itemID;
        oItem.ItemTypeId = itemType;
        oItem.ItemName = szName;
        oItem.ShoppingCartSessionId = currentSession.ID;
        oItem.Price = 1;
        context.ShoppingCartItems.AddObject(oItem);
        context.SaveChanges();
    }

    this.FlashInfo("Item added to shopping cart");
    ViewBag.Message(string.Format("Your shopping cart contains {0} item(s)",AnotherFunctionThatJustCountsTheValues()));
    return this.View();

}

The highlited line is where I get the userID, that function is just an extension function that does nothing complex, it just fetches the UserID which is saved as the FormsAuthenticationTicket.UserData field.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-08T04:37:46+00:00Added an answer on June 8, 2026 at 4:37 am

    // This is the section I’m worries about Guid gUserID = this.GetCurrentUserID();

    This is because normally this section has nothing to do inside your controller action. So let’s remove it, shall we? This way you will no longer have anything to worry about 🙂

    Let’s simplify your code first because it contains too much noise. By the way you should consider putting your controller action on a diet because it’s way too complicated and does too many things.

    The essential part is this:

    [Authorize]
    public ActionResult AddItem()
    {
        Guid gUserID = this.GetCurrentUserID();
        return Content(gUserID.ToString());
    }
    

    Now, that’s annoying indeed because if the GetCurrentUserID method resides in your controller and attempts to read the forms authentication cookie you might suffer to unit test it in isolation.

    What about if our code looked like this:

    [MyAuthorize]
    public ActionResult AddItem()
    {
        var user = (MyUser)User;
        return Content(user.Id.ToString());
    }
    

    where MyUser is a custom principal:

    public class MyUser : GenericPrincipal
    {
        public MyUser(IIdentity identity, string[] roles) : base(identity, roles)
        { }
    
        public Guid Id { get; set; }
    }
    

    Wouldn’t that be magnificent? This way the controller action has no longer to worry about cookies and tickets and stuff. That’s not its responsibility.

    Let’s see how we can unit test it now. We pick our favorite mocking framework (Rhino Mocks in my case along with MvcContrib.TestHelper) and mock:

    [TestMethod]
    public void AddItem_Returns_A_Content_Result_With_The_Current_User_Id()
    {
        // arrange
        var sut = new HomeController();
        var cb = new TestControllerBuilder();
        cb.InitializeController(sut);
        var user = new MyUser(new GenericIdentity("john"), null)
        {
            Id = Guid.NewGuid(),
        };
        cb.HttpContext.User = user;
    
        // act
        var actual = sut.AddItem();
    
        // assert
        actual
            .AssertResultIs<ContentResult>()
            .Content
            .Equals(user.Id.ToString());
    }
    

    So now all that’s left is take a look at how the custom [MyAuthorize] attribute might look like:

    public class MyAuthorizeAttribute : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            var authorized = base.AuthorizeCore(httpContext);
            if (!authorized)
            {
                return false;
            }
    
            var cookie = httpContext.Request.Cookies[FormsAuthentication.FormsCookieName];
            if (cookie == null)
            {
                return false;
            }
    
            var ticket = FormsAuthentication.Decrypt(cookie.Value);
            var id = Guid.Parse(ticket.UserData);
            var identity = new GenericIdentity(ticket.Name);
            httpContext.User = new MyUser(identity, null)
            {
                Id = id
            };
            return true;
        }
    }
    

    The custom authorize attribute is responsible for reading the UserData section of the the forms authentication cookie and setting the current principal to our custom principal.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have just tried to save a simple *.rtf file with some websites and
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
For some reason, after submitting a string like this Jack’s Spindle from a text
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I am trying to render a haml file in a javascript response like so:
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
I have an MVC Razor view @{ ViewBag.Title = Index; var c = (char)146;

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.