如何设置伪控制器上下文和httpsession

时间:2016-08-30 12:59:29

标签: nunit fakeiteasy

我正在使用NUnit并轻松搞定。 我打算在整个项目中重复使用安装程序。

这是我的setupCode:

IClient fake;
SampleController sController;
[SetUp]
public void Setup()
{
    sController = new SampleController();
    fake = A.Fake<IClient>();
    fakeContext =new  FakeContext(sController);

    sController = new SampleController(fake);
}

这是我的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;
         }
    }
}

在安装过程中,当我传递需要伪造的控制器时,我能够获得传递的控制器的伪控制器上下文。 此外,我希望HttpSessionStatebase在TestSetup期间也与上下文一起伪造,因此我不需要为单元测试方法中的每个调用伪造HttpSession。

 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);
}

如果我在Test方法中伪造HttpSessionStatebase,那么我就能得到fakeHttpSession。

有没有办法伪造HttpSessionState(fakeHttpSession)和hte控制器上下文一次,以便在我的程序集中的每个测试中使用相同的实例?

0 个答案:

没有答案