Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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));
}
like image 572
Steinar Herland Avatar asked Nov 24 '25 17:11

Steinar Herland


1 Answers

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 ;)

like image 95
IgorL Avatar answered Nov 26 '25 22:11

IgorL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!