简体   繁体   中英

Mocking ControllerContext could not find reference

The problem emerged as a result of this question. I did the following things:

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.Object;

Any ideas why using System.Web.Http.Controllers.HttpControllerContext; is not available in my test project.

You are using the wrong packages and the wrong namespaces.

It seems to me that you need to mock System.Web.Http.Controllers.ControllerContext , but you are providing a mocking instance of System.Web.Mvc.ControllerContext which is not the Web API class, but the ASP.NET MVC one.

What to do:

  1. Ensure you have installed Web Api package into your Unit Test Project:
    Install-Package Microsoft.AspNet.WebApi

  2. Remove any reference of MVC assemblies from your Unit Test Project (of course do this only if you do not need to test MVC components)

  3. Ensure you are importing the correct namespaces (and not the MVC ones) inside your Unit Test class:
    using System.Web.Http.Controllers;

Please be aware that even if the class names are the same, MVC components and Web API components are not interchangeable. Always verify you are using the correct ones inside your project.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM