I am using NUnit and Fake it easy. I am planning to Setup which can be reusable across the project.
here is my setupCode:
IClient fake;
SampleController sController;
[SetUp]
public void Setup()
{
sController = new SampleController();
fake = A.Fake<IClient>();
fakeContext =new FakeContext(sController);
sController = new SampleController(fake);
}
here is my FakeContextClass:
public class FakeContext
{
HttpSessionStateBase fakeHttpSession;
HttpContextBase fakeHttpContext;
ControllerContext ControllerContext;
public FakeContext(Controller controller)
{
try
{
fakeHttpSession = A.Fake<HttpSessionStateBase>();
fakeHttpContext = A.Fake<HttpContextBase>();
fakeHttpSession.Contents["TestSession"] = new SaSession()
{
DefaultUID = 1,
Name = "system",
LastName = "Test",
};
var fake = (SaSession)fakeHttpSession.Contents["TestSession"];
A.CallTo(() => fakeHttpContext.Session).Returns(fakeHttpSession);
A.CallTo(() => fakeHttpSession["TestSession"]).Returns(fake);
ControllerContext = new ControllerContext(fakeHttpContext, new RouteData(), A.Fake<ControllerBase>());
controller.ControllerContext = ControllerContext;
}
}
}
During Setup, when I pass controller which needs to be faked, I am able to get faked controller context of the passed controller. Also I want the HttpSessionStatebase also to be faked along with the context during TestSetup,so i don't need to fake the HttpSession for every call in the unit test methods.
My test Method:
[Test]
public async Task DetailsView()
{
int UID = 0;
string Name = "MedPlus";
A.CallTo(() => fake.GetDataAsync<IEnumerable<Group>>(fakeHttpSession, "/ManagementSvc/v1/Groups?UID=" + UID ));
////Act
var actionResult = await sController.DetailsView(UID,Name);
var viewResult = actionResult as ViewResult;
var grpModel = viewResult.Model as Model;
//Assert
Assert.IsNotNull(actionResult);
Assert.AreEqual("GrpDetails", viewResult.ViewName);
Assert.IsInstanceOf(typeof(Model), viewResult.Model);
}
If I fake HttpSessionStatebase in Test method,then I am able to get the fakeHttpSession.
Is there a way to fake HttpSessionState(fakeHttpSession) and hte controller context once so that the same instances are used in every test in my assembly?