I'm testing a Spring Boot Service, and there's one pretty much weird function that needs to be tested. I've made a test that runs successfully, but I'm not getting much coverage. Here's a function I'm testing:
protected String setQueryListField(List<String> model, String fieldName) {
String query = "";
if (model.contains("is blank") && model.size() > 1) {
for (String value : model) {
if (value.equals("is blank")) {
query = query.concat(" AND (" + fieldName + " = null");
} else if (model.size() == 2) {
query = query.concat(" OR " + fieldName + " CONTAINS('" + value + "'))");
} else {
if (model.indexOf(value) == 1) {
query = query.concat(" OR " + fieldName + " CONTAINS('" + value + "', ");
} else if ((model.indexOf(value) + 1) == model.size()) {
query = query.concat("'" + value + "'))");
} else {
query = query.concat("'" + value + "', ");
}
}
}
} else if (model.contains("is blank") && model.size() == 1) {
query = query.concat(" AND " + fieldName + " = null");
} else {
query = query.concat(" AND " + fieldName + " CONTAINS('" + String.join("','", model) + "')");
}
return query;
}
And here is a test I wrote. It runs successfully, as I said, but I'd like to get more coverage. Do you have any suggestions?
@Test
@DisplayName("setQueryListField Test")
void setQueryListField() {
List<String> stringList = new ArrayList<>();
stringList.add("is blank");
VaultService vaultService = Mockito.spy(vaultServiceTest);
doReturn("", "").when(vaultService).setQueryListField(stringList, "field__name");
String response = vaultService.setQueryListField(stringList, "field__name");
System.out.println(response);
stringList.add("test");
String secondResponse = vaultService.setQueryListField(stringList, "external__c");
System.out.println(secondResponse);
}
You are only covering the following if block
else if (model.contains("is blank") && model.size() == 1) {
query = query.concat(" AND " + fieldName + " = null");
}
If you need more coverage you need to try with other inputs so that it covers other branches too. For example, with model.size() > 1.
Also, the following lines are no op as it's mocking the same function that you are trying to test.
VaultService vaultService = Mockito.spy(vaultServiceTest);
doReturn("", "").when(vaultService).setQueryListField(stringList, "field__name");
String response = vaultService.setQueryListField(stringList, "field__name");