2

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;
Community
  • 1
  • 1
StefanL19
  • 1,476
  • 2
  • 14
  • 29

1 Answers1

1

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

Roman Marusyk
  • 23,328
  • 24
  • 73
  • 116