简体   繁体   中英

Custom SynchronizationContext to set Thread.CurrentPrincipal asynchronously in unittest

This question is similar to Set Thread.CurrentPrincipal Asynchronously? . However, 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));
}

Check if after

await SetCurrentPrincipalAsync();

the thread is not changed, because if SynchronizationContext.Current == null (and by default its equals to null, except UI thread etc.) after await execution will continue in any available in thread pool thread. Another recommendation, change all system classes, like HttpContext, with mock objects, test your code and not the system ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM