Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to moq HttpContext on Asp net Core

I have an asp .net core project, and practically in each action we use session, my question is how to test it if I don't have sessionRepository. Controller tests crush because session in controller is null. I try to Moq IHttpContextAcessor and it also doesn't work.

I try this:

HttpContext.Current = new HttpContext(new HttpRequest(null, "http://tempuri.org", null), new HttpResponse(null));

but HttpContext doesn't contain the definition for Current. (using Microsoft.AspNetCore.Http;)

Is there any way to moq or test controllers that use HttpContext and sessions?

like image 280
BASKA Avatar asked Oct 30 '25 01:10

BASKA


1 Answers

You can use ControllerContext to set the context to be DefaultHttpContext which you can modify to your needs.

var ctx = new ControllerContext() { HttpContext = new DefaultHttpContext()};
var tested = new MyCtrl();
tested.ControllerContext = ctx;
like image 73
tymtam Avatar answered Oct 31 '25 16:10

tymtam