dimanche 24 juillet 2016

Unit testing mvc model with HttpContext.Current.User.Identity.GetUserId()

In my MVC5 application, I have a Log entity, that is used to log any call to any controler. This log uses: HttpContext.Current.User.Identity.GetUserId() to detemend the identity of the user accesing the controle

public class Log

{
    public Log()
    {
        TS = DateTime.Now;
        UserId = HttpContext.Current.User.Identity.GetUserId();
    }

    [Required]
    public Int32 Id  { get; set; }
    public string UserId { get; set; }

    [Display(Name = "TS", ResourceType = typeof(Resources.Models.Log.Log))]
    [Required(ErrorMessageResourceType = typeof(Resources.Models.Log.Log), ErrorMessageResourceName = "RequiredTS")]
    public DateTime TS { get; set; }

    [Required]
    public short LogTypeId { get; set; }

    [Display(Name = "LogText", ResourceType = typeof(Resources.Models.Log.Log))]
    public string LogText { get; set; }

    public ApplicationUser User { get; set; }
}

}

When I try to unit test a controller and crating an instance of the log class I get this error:

threw exception: System.NullReferenceException: Object reference not set to an instance of an object. at DASU.Core.Models.Log..ctor()

I know this is because the context is not set.

So my question is how do I set the context, or how do I mock the context, so I can create the Log for my test?

Hope you can help me out here.

Kindly

Kåre

Aucun commentaire:

Enregistrer un commentaire