git clone https://github.com/fliglio/rest-gs.git
That was easy, right? What did we just do?
make test runs two sets of tests, “unit” and “component.” The unit tests should
be familiar, they’re just a suite of tests located in src/test/unit/
that we point phpunit at.
The component tests are a little different however.
Testing a service’s REST API is especially useful with microservices.
Low level tests are less useful than they are with a monolith for protecting against regression bugs
(because there isn’t a sprawl of code depending on any of these libraries.)
Instead of other components in our system relying on library interfaces however,
we have other services relying on our REST API. As long as we ensure our REST API doesn’t
change unintentially, we are pretty close to regression proof!
(That’s an oversimplification, but the point remains that the REST API is the
most important thing to test.)
The heart of the component-test make task (which gets used when you run make test)
is a Docker container built from the fliglio/local-dev image
(The same container we used in Microservices in PHP with Fliglio
to run our service for local exploratory testing.)
Write some tests
Now that we can automate running an environment with Docker and our Makefile,
All we have to do is write some tests against it.
(you’ll of course also want to test error cases and all your methods…)
Mocking external resources
Up to here, we’ve really been talking about integration testing our application, but
sometimes you either don’t have control of certain resource dependencies or you have a spidering web of transitive
service dependencies that aren’t practical to run for local test.
This entry point is the same as the normal index.php except we are configuring
the DemoApplication with TestDemoConfiguration. Since we wire up most of our
application in this class, we can mock individual components here to simplify
our environment and eliminate components that don’t need to be tested by us.
By mocking the WeatherClient class, we can both remove our dependence on an external resource
and ensure that the cities we use in our tests return consistent responses.
This technique can also be used to mock clients to your own services. A typical application
built with microservices will be comprised of several services and you shouldn’t have to
be running them all in order to test the REST API of the one you’re working on.
Hopefully I’ve given you a good idea of how to effectively test Fliglio microservices and
protect them against regression.