Question

i have a method which takes in a DotNetOpenAuth (formally known as DotNetOpenId) Response object. My method extracts any claimed data, checks to see if this user exists in our system, yadda yadda yadda... and when finished returns the auth'd user instance.

Now .. how can i use moq to mock up this response object, to test my authentication method ( AuthenticateUser() )?

switch (response.Status)
{
    case AuthenticationStatus.Authenticated:

    User user = null;
    try
    {
        // Extract the claimed information and 
        // check if this user is valid, etc.
        // Any errors with be thrown as Authentication Errors.
        user = _authenticationService.AuthenticateUser(response) as User;
    }
    catch (AuthenticationException exception)
    {
        ViewData.ModelState.AddModelError("AuthenticationError", exception);
    }

    .. other code, like forms auth, other response.status' etc. ..
}

Mocking framework: moq
Language: .NET C# 3.5 sp1
Response object: taken from the DotNetOpenAuth framework

Was it helpful?

Solution

I'm not familiar with Moq in particular, but the response object is a type that implements DotNetOpenAuth.OpenId.RelyingParty.IAuthenticationResponse, so it can be easily mocked by creating a class that implements the same interface and is prepared to return the same kinds of values.

...just downloaded Moq and mocked up an IAuthenticationResponse like so:

var response = new Mock<IAuthenticationResponse>(MockBehavior.Loose);
response.SetupGet(r => r.ClaimedIdentifier)
        .Returns("http://blog.nerdbank.net/");
response.SetupGet(r => r.Status)
        .Returns(AuthenticationStatus.Authenticated);
response.SetupGet(r => r.FriendlyIdentifierForDisplay)
        .Returns("blog.nerdbank.net");

IAuthenticationResponse resp = response.Object;
Console.WriteLine(resp.ClaimedIdentifier);

Obviously rather than send the result to Console.WriteLine you would want to pass the resp object to the method you're testing.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top