views:

276

answers:

1

Hi folks,

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

+1  A: 

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.

Andrew Arnott
Hi Andrew - love the library! So, i should make a TestAuthenticationResponse object which impliments IAuthenticationResponse and just hard code the various fields i expect?
Pure.Krome
Thanks. You could... although I just tried out Moq and updated my answer to show that you don't have to build this class that implements the interface yourself. Enjoy.
Andrew Arnott
<3 Andrew :) All this Moq stuff totally confuses me :( So i sincerly thank you for your time in dl'ing moq, etc. Would we see any Moq tests in the MVC sample RP project, in the future (re: DotNotOpenAuth Visual Studion solution) ? :)
Pure.Krome
That sounds like a good idea. Can you submit it to http://dotnetopenauth.uservoice.com so I don't forget about it?
Andrew Arnott