Mocking a cotroller context asp 4.5

百般思念 提交于 2019-12-10 11:14:58

问题


I have to mock the controller context in order to test some methods that are authorized. The problem is that although I try this it does not work because when I type:

var mock = new Mock<ControllerContext>();

Visual Studio underlines ControllerContext and says that

The type or namespace could not be found

These are the usings i have included in the unit test class: using Microsoft.VisualStudio.TestTools.UnitTesting;

    using System;
    using System.Web;
    using System.Collections.Generic;
    using Moq;
    using System.Web.Http.Controllers;
    using Data.Contracts;
    using System.Linq;
    using Web.Api.Controllers;

Any ideas how to include ControllerContext in the MSDN documentation they say that it is part of System.Web but it does not seem to be working. Also it will be great if there is another way to mock the context without using this.

I fixed the reference by intalling the Mvc package. But now receive the following error when I try this:

var mock = new Mock<ControllerContext>();
            mock.SetupGet(x => x.HttpContext.User.Identity.Name).Returns("SOMEUSER");
            mock.SetupGet(x => x.HttpContext.Request.IsAuthenticated).Returns(true);
            controller.ControllerContext = mock.Object; 

Cannot convert System.Web.Mvc.ControllerContext to System.Web.Http.Controllers.ControllerContext

> controller.ControllerContext = mock.Objectt;

回答1:


ControllerContext is a part of System.Web.Mvc in System.Web.Mvc.dll. Just add reference to it



来源:https://stackoverflow.com/questions/37432795/mocking-a-cotroller-context-asp-4-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!