Mocking ADAL for Unit Tests
Rate this post

Active Directory Authentication Library (ADAL) provides developers with great experiences to easily integrate Azure Active Directory (AAD) with their application for authentication and authorisation. With minimum efforts, we can implement OAuth authentication against AAD, using ADAL. However, in the unit testing world, it’s not that easy to test application when the application uses ADAL because ADAL is not unit-testable. We don’t test ADAL itself, but we do need mock it to test applications using ADAL. In this post, we are going to implement how to implement wrapper classes for ADAL’s AuthenticationContext, AuthenticationResult and DeviceCodeResult.

Sample codes used for this post can be found at

As you have already been aware, AuthenticationContext is a sealed class – we can’t inherit this nor add an interface for mocking. In order to make it mockable, we should implement a wrapper class called AuthenticationContextWrapper implementing IAuthenticationContextWrapper, with the same signature of the AuthenticationContext class. Here’s an interface.

And here’s the class implementing the interface above.

As you can see the code above, the wrapper calls an original method of the AuthenticationContext instance and returns a wrapped result. Let’s use these wrappers in our test codes.

If we use the original ADAL, we wouldn’t be able to mock those instances – AuthenticationContext and AuthenticationResult. Now, we use wrapper classes for both and are able to mock them. Do you think those wrapper make our lives easier? This NuGet package will even more help us.

Application Development and Integration, Azure Infrastructure, Security, Testing
, ,

Leave a Reply

newest oldest most voted
Notify of
Michael Freidgeim
Michael Freidgeim

You should show how to use wrapper instead of AuthenticationContext in application code, not only in test

Andy Palmer
Andy Palmer

Creating a wrapper is the typical pattern when a dependency can’t be stubbed. It’s an annoyance, though, that Microsoft didn’t consider testing with ADAL. My answer has been to just not use this library and to call MS’s OAuth2 APIs directly.

Reimplementing ADAL’s basic functionality actually seems to be less code than creating the new interfaces and delegation classes, not all of which you actually show, and which, by the way, are not testable in and of themselves.

Follow Us!

Kloud Solutions Blog - Follow Us!