I am writing unit test for controllers in an asp.net core web application, it uses Identity framework for authentication. I was able to create an authenticated HttpClient with valid bearer token. But when the client tried to GetAsync from an endpoint that is policy protected (e.g. RequireRole("Admin")), it always fails with error 500, but if I make that endpoint [AllowAnonymous], it will work. I've tried using SignInManager to sign in first, thinking that will provide the context user, still the same. So, how to use GetAsync to access a policy protected endpoint in unit test?
Asked
Active
Viewed 100 times
0
For Comment
- 1,139
- 4
- 13
- 25
-
Hi @for-comment, you need `integration test` for this. Because this attribute processes the request pipeline by framework and you could not test it with `unit tests`. You need to start up your service `new TestServer(...)` in memory and test it. Please, check this [answear](https://stackoverflow.com/questions/48562403/unit-testing-an-authorizeattribute-on-an-asp-net-core-mvc-api-controller). And we can close it like *duplication* – DarkSideMoon Jan 09 '21 at 11:38
-
this is part of the integration tests, it is generating the in-memory server with `WebApplicationFactory.CreateClient()`, which generates the authenticated client, also the auto generated test DB already contains the test user's credential that has the admin role. – For Comment Jan 11 '21 at 15:39