Authentication in integration testing
The most frustrating part of creating integration tests is working with authentication. There are two approaches. The first approach is this: we simply duplicate the same authentication code that is in our API. This is especially straightforward if we are using a stateless JWT authentication token. We create the same token in the same way as we do in our API and add it to HttpContext
. Then, we use normal HTTP requests in our integration tests. The system under test goes through its normal authentication process. The advantage is we have a lot of fine-grained control. The disadvantage to this setup is that it is extremely brittle. If any detail of authentication changes in our API, we have to duplicate that same code exactly the same way in our integration tests.
The other option is to create a custom authentication handler. When WebApplicationFactory<T>
starts our API in test, we temporarily override the normal authentication service....