Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC Is it ok to access HttpContext.Current.User in model and how to test

on one of my model class I have the property:

public virtual bool OkToChangeApprovedForPayment
        {
            get
            {
                return ExportedDateTime == null && PMApproved == true && HttpContext.Current.User.IsInRole(Resources.Roles.VectorOpsAdmin);
            }
        }

As you can see one of the conditions is testing the role the user is in. Is it ok to be accessing the HttpContext in the model like this? If not what is a better way to do it?

If it is ok, how would you unit test it? How would you replace the call to the HttpContext?

like image 317
AnonyMouse Avatar asked Nov 22 '25 14:11

AnonyMouse


1 Answers

This is safe (if your model executes in the context of a running request, of course).

It will be hard to test, though. You could inject an instance of HttpContextBase into the model which is more suitable for testing.

like image 141
usr Avatar answered Nov 25 '25 09:11

usr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!