jeudi 25 mai 2023

Designing classes to help Junit Testing

I will try to explain through pseudocode a code quality or design issue that I encountered while testing a spring boot application:

controllerMethod(@RequestParam(version) String version){

 service.generateFile(version)


}

class Service {

private map= new HashMap<>();

void generateFile(version){
String rVersion = fetchRversion(version);
String json=makeApiCall(url+rVersion);
build(map);
generateData(json)

}
generateData(json){
// uses map
}

The above way of coding cause trouble when testing the generateData method. So if I have the JSON, I pass it to the generateData function. The trouble will be that map is built inside the generateFile function.
So it won't work. Either I built the map inside the test function for generateData or there could be some way of creating the Service class object with the map so that no testing function has to care about building or instantiating any other data. Since the version is passed at run time and based on that the map is built, will it be appropriate to have a separate build function inside the service class which can be called to setup all the required things?
Any alternative to this approach?

Aucun commentaire:

Enregistrer un commentaire