I'm trying to practice TDD and have an exercise to do. There is an existing service deployed somewhere in internet having public RESTful api. Each request to this api requires some data preparation like valid request string construction, some encryption, some body message formatting etc. I'd like to write generic client for this service using TDD.
I know it is not as simple as e.g. StringCalculator kata, and requires a bit different approach.
I don't know how to start with that. I'd like to test it without using real service, so there is kind of fake impl required. Is it better to write some fake implementation, deploy it on localhost and call it from my tests? Or maybe mock a class responsible for sending http request?
I'd like my client usage to be as below:
public class ServiceClientTest {
@Test
public void testSendStoreRequest() {
ServiceClient client = new ServiceClient("app_key", "private_key")
ClientResponse response = client.sendStoreRequest(StorageType.NORMAL, "string_to_store");
assertEquals("200", response.getStatus());
}
}
Can you point me any direction on how to start with this? Should I start bottom-up and writing all the components (for request string creation, for encryption etc) and then use them all in ServiceClient, or should I start from ServiceClient test and implementation with top-down and mocking?
First of all, don't mock external APIs. Why? Cos you don't own them.
The ideal solution for your problem seems to be what you started describing. You should create an interface in your project that you own, that will represent the external service.
public interface CalculatorService {
int add(int a, int b);
}
This will be your border for testing. All your UNIT and ACCEPTANCE tests should run against a mock or stub of CalculatorService
. They will be fast.
You can do that since it is you who defines that contract (what that interface actually means).
Later, you will have an implementation that goes to that remote HTTP rest service:
class RemoteRestCalculator implements CalculatorService {
public int add(int a, int b) {
// call the remote service in here
}
}
You need to test this contract (border). So you will write integration tests just for the RemoteRestCalculator
. You can also have couple of end-to-end tests that run application with the RemoteRestCalculator
to test the wiring, etc.
Now, to answer you question, how to test that RemoteRestCalculator
?
RemoteRestCalculator
that run against that instance.
RemoteRestCalculator
that run against that simulator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With