How can I mock Server.HtmlEncode

2019-04-09 10:39发布

问题:

I am trying the following, but I am getting : Object reference not set to an instance of an object.

 HttpContextBase mockContext = MockRepository.GenerateMock<HttpContextBase>();

 mockContext.Expect(c => c.Server.HtmlEncode("")).IgnoreArguments().Return("");
 mockContext.Expect(c => c.Server.HtmlDecode("")).Return("");

 controller.ControllerContext = 
    new ControllerContext(mockContext, new RouteData(), controller);

Matin,

Thanks. That was enough to point me in the right direction provided here:

var mockContext = MockRepository.GenerateMock<HttpContextBase>();       
var mockServer = MockRepository.GenerateMock<HttpServerUtilityBase>();

mockServer.Expect(s => s.HtmlEncode(""))
    .IgnoreArguments()
    .Repeat.AtLeastOnce()
    .Return("");

mockContext.Expect(c => c.Server)
    .IgnoreArguments()
    .Repeat.AtLeastOnce()
    .Return(mockServer);

controller.ControllerContext = 
    new ControllerContext(mockContext, new RouteData(), controller);

回答1:

Pure guess here:

var mockServer = MockRepository.GenerateMock<HttpServerUtilityBase>();
mockServer.Expect(x => x.HtmlEncode("")).IgnoreArguments().Return("");