-1

I have the following controller action

        [Route(ActionName.Create)]
        public async Task<ActionResult> Create()
        {
            .... 
            if (!UserContext.Roles.HasFlag(GroupsEnum.Admin))
            {
                throw new UnauthorizedAccessException("Permission Denied");
            }
            ... 
        }

I have following in xxxxControllerTests.cs

        [TestMethod]
        public async Task Can_Request_Create()
        {

            ViewResult result = (ViewResult)await MockController.Object.Create();
            ...
            ...
        }

when I run the unit test I get unauthorized access exception raised. How can pass UserContext while mockController, so controller action will be executed with specific user context?

Amit Joshi
  • 15,448
  • 21
  • 77
  • 141
Developer
  • 25,073
  • 20
  • 81
  • 128

2 Answers2

1

Normally when you're instantiating the Controller you're testing, you can initialize it like this:

var controllerToTest = new MyController() {
    ControllerContext = new ControllerContext {
        HttpContext = //assign mock context,
        UserContext = //assign mock context
    }
};
var result = controllerToTest.Create();

However this line of code makes me think you're testing an already mocked controller:

ViewResult result = (ViewResult)await MockController.Object.Create();

The .Object call makes me think you have a Mock<MyController> in there and that's not right. You're not testing your own controller.

Simmetric
  • 1,443
  • 2
  • 12
  • 20
  • Thanks, @Simmetric, clue you provided give me an idea of how to fix it. all fixed now :). I will update the question with the solution. Thanks. – Developer Feb 16 '21 at 23:19
-1

You should Mock your dbContext.

[https://stackoverflow.com/questions/54219742/mocking-ef-core-dbcontext-and-dbset][1]

Ederson
  • 49
  • 5