Skip to content

Provide unit test capabilities #389

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
cracksalad opened this issue Mar 19, 2025 · 0 comments
Open

Provide unit test capabilities #389

cracksalad opened this issue Mar 19, 2025 · 0 comments

Comments

@cracksalad
Copy link

I guess a pretty common use case for this project is to create a proxy/adapter for some HTTP based API. This would for example look like this:

class OpenWeatherMapProxy {
  
  private readonly HttpClient $client;
  
  public function __construct(#[\SensitiveParameter] string $apiKey, string $lang = 'en') {
    $this->client = (new HttpClientBuilder())
        ->retry(3)
        ->intercept(new AddRequestHeader('Accept', 'application/json'))
        ->intercept(new ModifyRequest(function(Request $request) use($apiKey, $lang): Request {
          $request->setQueryParameter('appid', $apiKey);  // add API key to every request
          $request->setQueryParameter('units', 'metric'); // add preferred unit system to every request
          $request->setQueryParameter('lang', $lang);     // add preferred language to every request
          return $request;
        }))
        ->build();
  }

  // [...]
}

Now, how to unit or integration test this?
Note: we do not want to actually send requests, since the API might have a strict rate limit or is priced per API call. In addition, that would miss the point of unit and integration tests.

Approaches:

  • Refactor the class to utilize Dependency Injection pattern: This would move the whole HttpClientBuilder part to the caller, which is weird, since we do some API specific things there. Or is there a way to extend a HttpClient with interceptors and stuff after its initial build? Maybe using new InterceptedHttpClient($paramClient, $myInterceptor1)?
  • Insert a mocked HttpClient into the proxy and replace the $client using Reflection: This would make it impossible to test the HttpClient settings from the constructor and it is impossible due to readonly, which - apart from that - makes absolutely sense here.

Either way, in my opinion there should be a way to test stuff like this and it should be documented how to do it properly in the README.md. Thanks for helping me out here!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

1 participant