Can I change the HTTP user agent when writing browser tests? My module has some special functionality based on the user agent of the request. I want to write tests for this functionality based on D8's BrowserTestBase, but it doesn't seem possible to change the user agent string.

The prepareRequest method of BrowserTestBase sets the user agent to the value of drupal_generate_test_ua($this-&gt;databasePrefix).

For a test, I tried changing this value to something else, and it breaks the tests.

Now I realize that there appears to be some functionality built into core based on this value that drupal_generate_test_ua returns and there's checks all over core to detect if Drupal is running within a test or not.

Is there a workaround or any hope for writing tests with a custom user agent?
No, you can't.

BrowserTestBase, just like other other tests that support web requests uses the user agent to identify which test environment you're in (there could be multiple, parallel ones). Changing the user agent would result in your request being sent against the main site.

The only workaround that I see is to send another header (if that's actually possible through the API, not sure). In your could you would then look at that header instead. It's not perfect and it requires you to write special code for tests, but I can't really see another way if you really rely on the user agent.