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 https://github.com/aliencube/Microsoft-ADAL-Wrapper
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.
You should show how to use wrapper instead of AuthenticationContext in application code, not only in test
@Michael Thanks for the comment.
As the usage of `AuthenticationContextWrapper` is basically the same as `AuthenticationContext`, you can replace your `AuthenticationContext` with `AuthenticationContextWrapper` in your application code. The only difference between two is the wrapper is testable while the original one is not.
HTH
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.
@Andy Thanks for your comment!
You spot on. ADAL keeps evolving and has become more testable than before.