ASP.NET MVC unit test controller with HttpContext

前端 未结 5 1334
攒了一身酷
攒了一身酷 2020-11-28 07:21

I am trying to write a unit test for my one controller to verify if a view was returned properly, but this controller has a basecontroller that accesses the HttpContext.Curr

5条回答
  •  孤街浪徒
    2020-11-28 07:36

    If you are using Typemock, you can do this:

    Isolate.WhenCalled(()=>controller.HttpContext.Current.Session["UserID"])
    .WillReturn("your id");
    

    The test code will look like:

    [TestMethod]
    public void Retrieve_IndexTest()
    {
        // Arrange
        const string expectedViewName = "Index";
    
        IndexController controller = new IndexController();
        Isolate.WhenCalled(()=>controller.HttpContext.Current.Session["UserID"])
        .WillReturn("your id");
        // Act
        var result = controller.Index() as ViewResult;
    
        // Assert
        Assert.IsNotNull(result, "Should have returned a ViewResult");
        Assert.AreEqual(expectedViewName, result.ViewName, "View name should have been {0}", expectedViewName);
    }
    

提交回复
热议问题