How do I mock controller context in my unit test so that my partial view to string function works?

前端 未结 2 1163
不知归路
不知归路 2021-02-07 13:34

I am attempting to create a unit test for my controller, but the action I am testing uses a partial view to string function which doesn\'t want to work in my tests.



        
相关标签:
2条回答
  • 2021-02-07 13:48

    Final solution thanks to help in the comments.

    var mock = new Mock<ControllerContext>();
    mock.SetupGet(p => p.HttpContext.User.Identity.Name).Returns(userName);
    if (userName != null)
    {
       mock.SetupGet(p => p.HttpContext.Request.IsAuthenticated).Returns(true);
       mock.SetupGet(p => p.HttpContext.User.Identity.IsAuthenticated).Returns(true);
    }
    else
    {
       mock.SetupGet(p => p.HttpContext.Request.IsAuthenticated).Returns(false);
    }
    
    var routeData = new RouteData();
    routeData.Values.Add("controller", "BlogController");
    mock.SetupGet(m => m.RouteData).Returns(routeData);
    
    var view = new Mock<IView>();
    var engine = new Mock<IViewEngine>();
    var viewEngineResult = new ViewEngineResult(view.Object, engine.Object);
    engine.Setup(e => e.FindPartialView(It.IsAny<ControllerContext>(), It.IsAny<string>(), It.IsAny<bool>())).Returns(viewEngineResult);
    ViewEngines.Engines.Clear();
    ViewEngines.Engines.Add(engine.Object);
    
    var controller = new BlogController();
    controller.ControllerContext = mock.Object;
    
    0 讨论(0)
  • 2021-02-07 13:59

    Here's a version using AutoMoq that renders a string of your choice.

    Subject.ControllerContext = new ControllerContext(
        Mocked<HttpContextBase>().Object,
        new RouteData(),
        Subject);
    
    ViewEngines.Engines.Clear();
    ViewEngines.Engines.Add(Mocked<IViewEngine>().Object);
    Mocked<IViewEngine>()
        .Setup(x => x.FindPartialView(Subject.ControllerContext,
                                      It.IsAny<string>(), It.IsAny<bool>()))
        .Returns(new ViewEngineResult(Mocked<IView>().Object,
                                      Mocked<IViewEngine>().Object));
    Mocked<IView>()
        .Setup(x => x.Render(It.IsAny<ViewContext>(), It.IsAny<TextWriter>()))
        .Callback((ViewContext c, TextWriter w) => w.WriteLine("RENDERED"));
    
    0 讨论(0)
提交回复
热议问题