3

I have private property to access AuthenticationManager:

private IAuthenticationManager AuthenticationManager => HttpContext.GetOwinContext().Authentication;

I want to mock the method GetExternalLoginInfoAsync() in order to receive fake ExternalLoginInfo object:

ExternalLoginInfo loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

Both GetOwinContext() and GetExternalLoginInfoAsync() methods are extension methods. Is it possible to see source code of these methods to see how they works?

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
John Doe
  • 31
  • 1
  • If you want to mock GetExternalLoginInfoAsync(), why do you care about it source code and how it works? And in general, you don't have easy way to mock extension method. Check this (Moq specific) for details: http://stackoverflow.com/questions/2295960/mocking-extension-methods-with-moq – CodeFuller May 17 '17 at 15:50
  • If you want to mock Extension or static methods then you need to use licensed libraries such as TypeMock or RhinoMock .. Moq doesn't support this. – Venkata Dorisala May 17 '17 at 15:51
  • I want to try mocking objects that are used inside these extension methods to change behaviour of these methods, but without source code I don't know what they are using and how. – John Doe May 17 '17 at 16:15

1 Answers1

3

Both GetOwinContext() and GetExternalLoginInfoAsync() methods are extension methods. Is it possible to see source code of these methods to see how they works?

Sure, one way is to use ILSpy. For example:

/// <summary>
///     Extracts login info out of an external identity
/// </summary>
/// <param name="manager"></param>
/// <returns></returns>
public static async Task<ExternalLoginInfo> GetExternalLoginInfoAsync(this IAuthenticationManager manager)
{
    if (manager == null)
    {
        throw new ArgumentNullException("manager");
    }
    return AuthenticationManagerExtensions.GetExternalLoginInfo(await TaskExtensions.WithCurrentCulture<AuthenticateResult>(manager.AuthenticateAsync("ExternalCookie")));
}

However, in my opinion this is just a Rabbit hole. Instead, you should be using Dependency Injection to inject a IAuthenticationManager into your controller. Then you can simply Mock it and the methods you need instead of testing internal microsoft code.

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
  • I was able to mock the extension response using `IAuthenticationManager` and mocking the following: `GetMock().Setup(x => x.AuthenticateAsync("ExternalCookie")).Returns(Task.FromResult(new AuthenticateResult(null, new AuthenticationProperties(), new AuthenticationDescription())));` – Electric Sheep Aug 11 '17 at 10:46