0

I think I have a design flaw in my application. I'll explain why.

I have a wrapper around a httpclient which gets injected (via php-di) in all kinds of other classes.

I use Slim to create an api. When call enters my application, Slim will guide it to the right controller, which has a httpclient injected. (in reality it's not he controller who has the httpclient injected, but I'm trying to keep it simple for the example)

Now to the unittesting(integrationtesting) part. I use a bootstrap file to initialize slim (with the php-di bridge). I have different files for each environment. So another class (stub, if you like), gets injected as the httpclient in the controllers.

So far so good. Now I want to change the outcome of this httpclient-stub to my wishes. Like this:

// Arrange
$request = ..;
$response = ..;
$httpclientStub->setResponseMessage($response);

//Act
$response = $app->process($request, new Response());

//Assert
..

Unfortunately, I cannot access $httpclientStub from within the test function. I use a singleton class now to pass variabled from tests, to the stubs. Which is fairly ugly.

Any suggestions for a better 'stub' solution?

sridesmet
  • 875
  • 9
  • 19
  • 1
    By default the container entries are "frozen". I use reflection to "inject" mocks into the container (only for integrations tests). [Example with Pimple](https://github.com/odan/prisma/blob/master/tests/ApiTestCase.php#L169) – odan Apr 11 '18 at 14:06
  • Looks like it wasn't frozen after all. I used getContainer() on $app, and I'm able to set classes in it. – sridesmet Apr 11 '18 at 14:39

1 Answers1

0

I used the following method, which doesn't require the use of a singleton at all. We change the container while the test is running. It feels alot less hacky.

public function setResponseMessage(HttpMessage $response)
    {
      $httpClient = new \Stub\HttpClientStub();
      $httpClient->setResponseMessage($response);

      $container = $this->app->getContainer();
      $container->set(\Helper\IHttpClient::class, $httpClient);
    }
sridesmet
  • 875
  • 9
  • 19