Skip to content

Managing lifecycle of HttpContext in integration tests when running in parallel #1213

Answered by dukesteen
dukesteen asked this question in Q&A
Discussion options

You must be logged in to vote

For any other people looking to do the same thing, you have 2 options:

Option 1: Create a custom implementation of IHttpContextAccessor and register it as scoped in your WebApplicationFactory<T>, then in your DependencyInjectionClassConstructor, inherit from ITestStartEventReceiver and add the following code

	public ValueTask OnTestStart(BeforeTestContext beforeTestContext)
	{
		var httpContextAccessor = _scope.ServiceProvider.GetRequiredService<IHttpContextAccessor>();
		httpContextAccessor.HttpContext ??= new DefaultHttpContext
		{
			RequestServices = _scope.ServiceProvider
		};

		return ValueTask.CompletedTask;
	}

This sets the HttpContext for the current scope with the correctly sco…

Replies: 3 comments 4 replies

Comment options

You must be logged in to vote
3 replies
@dukesteen
Comment options

@thomhurst
Comment options

@dukesteen
Comment options

Comment options

You must be logged in to vote
1 reply
@thomhurst
Comment options

Answer selected by dukesteen
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants