Hi, how do you best fake an rest api, i.e. a retro...
# test
u
Hi, how do you best fake an rest api, i.e. a retrofit interface? FakeApi subclass? If so, how? Do you create an anonymous subclass and override what you need per test? Or a final class and lambdas a ctor params (then called in the functions)?
t
What is it you’re actually trying to achieve?
u
integration test of sync routine api returns x, sync happens, assert database looks like y
t
So you’re testing an API?
Do you actually want to test the API gets called, or do you want to test the result is stored in a DB?
u
well, api in this case is just GET, so not really necessary to check explicitly if it was called
t
Standard approach - create an interface to represent your API class and provide a test double to the test
u
how, anonymous subclass and inline override whats needed or regular subclass with lambdas in ctor?
t
Just create an interface for your api instead of a concrete class. Use the interface wherever you use the current concrete class, then in tests you can just create any kind of test double
No need for subclasses or injecting lambdas
u
no I mean how do you create the test double, anonymous subclass or something else?
t
You just implement the interface I described above
u
so a single concrete implementation class, with all return values passed in via ctor? i feel like that will contain lot of unrelared setup, if ig were lambdas, you could throw in lambda, and have that as default param
t
You can do it whichever way you like. Just be aware that there isn’t a “one size fits all” solution. Return values in a constructor, hardcoded values, programmable values, lambda return, anything else - they all have their place. If you have a lot of setup to do just for a single test though you might want to look at your design. For example, if your
FakeApi
has loads of methods and you need to set that up, extract a smaller interface that your code under test needs and have your
FakeApi
implement that. You only need to do the setup required for your test then.
u
sure, most ergonomi would be anonymous subclass and override whats needed but i dont like the syntax
w
i use mock server when I want to avoid mocking out code in my runtime, and let it run like it does in production (ie integration test): https://www.mock-server.com/mock_server/running_mock_server.html#client_api