samedi 26 septembre 2015

Custom SynchronizationContext to set Thread.CurrentPrincipal asynchronously in unittest

This question is similar to Set Thread.CurrentPrincipal Asynchronously?. But in my case I am trying to get this to work in unit-tests, and hope to solve this with a custom SynchronizationContext.

Is there a SynchronizationContext that behaves similar to the one used by ASP.NET, but that can be used by unit-tests? (My code works perfectly fine in ASP.NET.)

In particular, it's the feature of the AspNetSynchronizationContext that enables a principal to "buble" out of async methods that I want.

When the method SetCurrentPrincipalAsync (bellow) is called in an asp.net application/context, the Thread.CurrentPrincipal will not be overwritten by the calling method. - But when the test is run, it will fail.

[Fact]
public async Task SetSynchronizationContext()
{
    //SynchronizationContext.SetSynchronizationContext(new SomeCustomSynchronizationContext());
    await SetCurrentPrincipalAsync();
    Assert.Equal("Name", Thread.CurrentPrincipal.Identity.Name);
}

static async Task SetCurrentPrincipalAsync()
{
    var principal = new GenericPrincipal(new GenericIdentity("Name"), new []{"Role"});
    Thread.CurrentPrincipal = principal;
    if (HttpContext.Current != null)
        HttpContext.Current.User = principal;
    await Task.Delay(TimeSpan.FromSeconds(1));
}

Aucun commentaire:

Enregistrer un commentaire