Thursday, May 07, 2015

Use Caching Service as Mocked Microservices

For a long period of time, we've been using mocking framework to ease unit testing. The idea behind is,
  • in production, object A's method a() calls object B's method b()
  • in test, we
    • pre-define b()'s behaviour
    • inject mocked object B into object-under-test A
    • fire a() and verify the output
With the shift from monolithic style to microservices oriented software design, we call remote APIs (RESTful or RPC) more often than we did before. Quite a few HttpMock products were created to allow us to test remote APIs the way we used to test local APIs.

But if we have a real HTTP server somewhere, in order to mock response from remote, all we need is to set up endpoint with the response and later tear it down. As a side-product, caching service is such a HTTP server that can easily be used to mock remote APIs object-under-test consume. It works this way
  • in product, object A's method a() send HTTP request to service B's endpoint b
  • in test, we
    • pre-populate (POST) expected response in cache server for endpoint b
    • send (GET) HTTP request to it (instead of the production endpoint) from A.a()
    • get response from cache server and verify a()'s output
    • remove (DELETE) the response from cache server
Now you see how the idea of microservices may also change the way you test your microservice oriented production code.

Happy testing!

No comments:

Post a Comment