Kol
Kol

Reputation: 47

How to get my Unit Tests to bypass the Authorize tag on my .NET Web Controller

I have a Web API in .NET 4.6.1 and my controllers are Azure B2C protected. Hence, they have the [Authorize] tag.

I wrote a Unit Test to ensure that I can hit the route and test some business logic. However, I cannot figure out how to bypass the [Authorize] tag and I do not want to authorize with B2C for each unit test that runs.

I am assuming that mocking the Controller Context would be a good start but I am having trouble figuring out the syntax.

There are a few articles about mocking the ControllerContext and then setting the HttpContext.Request.IsAuthenticated but this applies to MVC.

I get an error converting from System.Web.MVC.ControllerContext to System.Web.Http.Controllers.HttpControllerContext.

Cannot implicitly convert type error:

Cannot implicitly convert type error

I am hoping that someone can help me figure out how to bypass the [Authorize] tag for my unit tests?

Upvotes: 1

Views: 1272

Answers (2)

martijn
martijn

Reputation: 1469

If you run your tests in debug, it's possible to bypass the authorization attribute by using preprocessor directives. You can use these to remove certain parts from compilation in debug mode (or release mode). The following example shows how to remove the authorization attribute in DEBUG mode, while leaving it in in RELEASE mode

#if !DEBUG
[Authorize]
#endif
public class MyController : Controller
{
    // controller logic
}

I would advise to read more about preprocessor directives before using them. This sollution is very dependent on the mode in which the tests are run.

Upvotes: 0

Peter Davidsen
Peter Davidsen

Reputation: 678

It looks like you have different usings in your file, so your mock is a

Mock<System.Web.Mvc.ControllerContext>

And not a

Mock<System.Web.Http.Controllers.HttpControllerContext>

If you specify the namespace, that can fix that problem.

I would however split up the tests instead, moving your business logic from an authorised controller and into its own class you can more easily test.

And I'm sure there are ways of testing your routes.

Upvotes: 1

Related Questions