Answer the question
In order to leave comments, you need to log in
How to test a module that receives data from external services?
Hello.
There is a specific function that requests a "job" from an external resource. Both the request and the parsing of the response go inside the function.
How can / should I write a test to check the work in case of receiving / not receiving certain data?
Thanks in advance.
Answer the question
In order to leave comments, you need to log in
Move response parsing into a separate function/method/module so that you can test it independently.
As for the request, the easiest way is to cover it with e2e tests. Well, or explicitly transfer to your function the thing that makes requests in your language / platform (for example, in client JS it is XMLHTTPRequest or fetch), and replace it in tests.
As usual - come up with test data, and then work with them. Dependencies that are not directly related to the logic being tested can be directly mocked (in Java, I use Mockito, for your case, I also think there is something that makes life easier). The example below may be of some use to you.
import org.junit.Assert;
class Test {
public static void main(String[] args) {
String message = "Hello, World!\nCheck this message.";
ExternalController external = job -> {
System.out.println(job);
return job.toUpperCase();
};
InternalController tested = new InternalController(external);
String results = tested.processRequest(message);
Assert.assertEquals("HELLO, WORLD!\nCHECK THIS MESSAGE.\n", results);
}
}
class InternalController {
private ExternalController external;
InternalController(ExternalController external) {
this.external = external;
}
String processRequest(String message) {
String[] jobs = message.split("\n");
StringBuilder results = new StringBuilder();
for (String job : jobs) {
String result = external.doWork(job);
results.append(result).append("\n");
}
return results.toString();
}
}
interface ExternalController {
String doWork(String job);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question