Injecting HttpContext into FederatedAuthentication.SessionAuthenticationModule during unit test

344 views Asked by At

I need to run unit tests on a WebAPI project that authenticates the user using FederatedAuthentication.

This line throws an error, because HttpContext is null:

FederatedAuthentication.SessionAuthenticationModule.WriteSessionTokenToCookie(sessionSecurityToken);

Elsewhere, I'm using a helper to define the HttpContext:

public class HttpContextHelper
{
    private static HttpContextBase m_context;
    public static HttpContextBase Current
    {
        get
        {
            if (m_context != null)
                return m_context;

            if (HttpContext.Current == null)
                throw new InvalidOperationException("HttpContext not available");

            return new HttpContextWrapper(HttpContext.Current);
        }
    }

    public static void SetCurrentContext(HttpContextBase context)
    {
        m_context = context;
    }
}

And everywhere I would normally reference HttpContext.Current, I use HttpContextHelper.Current instead.

I've seen TypeMock Isolator mentioned on this thread: How to unit test code that uses FederatedAuthentication.SessionAuthenticationModule

The post suggests that I should use

Isolate.WhenCalled(() => FederatedAuthentication.SessionAuthenticationModule).WillReturn(<a fake value>);

But what do I put in /a fake value/??

I'm new to unit testing and so have never used mocking before, so some guidance would be appreciated. Thanks.

0

There are 0 answers