2
votes

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?

3
tnx i will try this. - BASKA
tymtam i set the HttpContext but now in controler i get an exception ``` Session has not been configured for this application or request. ``` - BASKA

3 Answers

7
votes

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;
1
votes

The controller has an Controller context which you can set (i used the default one) :

Controller.ControllerContext = new ControllerContext                                                
{
    HttpContext = new DefaultHttpContext()
};
0
votes

After time I think is bad idea to moq Session, better way is to create a IOC container, for example we create ISessionManager interface with methods which return stored in session objects:

public class SessionManager:ISessionManager{

public User GetUser(){
  User usr= JsonConvert.DeserializeObject<User>(HttpContext.Session.GetString("USER"));
  return usr;
}

***here we get data from session***

}

for UnitTest we just create a new class which implement ISessionManager and use it for test Controller's.

public class SessionManagerTest:ISessionManager{

public User GetUser(){
  User usr=new User();
  ...initialize all fields
  return usr;
}
******
}