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

前端 未结 2 1159
不知归路
不知归路 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:59

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

    Subject.ControllerContext = new ControllerContext(
        Mocked().Object,
        new RouteData(),
        Subject);
    
    ViewEngines.Engines.Clear();
    ViewEngines.Engines.Add(Mocked().Object);
    Mocked()
        .Setup(x => x.FindPartialView(Subject.ControllerContext,
                                      It.IsAny(), It.IsAny()))
        .Returns(new ViewEngineResult(Mocked().Object,
                                      Mocked().Object));
    Mocked()
        .Setup(x => x.Render(It.IsAny(), It.IsAny()))
        .Callback((ViewContext c, TextWriter w) => w.WriteLine("RENDERED"));
    

提交回复
热议问题