Issue
I am new to writing Unit tests. I saw few examples of jUnit , but they all were for functions returning a value.
I have to write unit test for following method. Also we are using objects and methods in this method not belonging to this class like ConfigParser and ParseConfig. How do i go about writing Unit tests for such menthods?
@RequestMapping(value = "/generate-json" , consumes = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST)
@PageType(pageType = "PlaceHolderPageType")
public void execute(@RequestBody String payload) throws JSONException {
JSONObject json = new JSONObject(payload);
JSONObject configJSON = generateJSONSchema(json.toString());
String capabilityName = (String) configJSON.get(JSONConfigurationConstants.CAPABILITY_NAME);
String fileLocation = FormInputFieldConstants.JSON_PATH + capabilityName + JSONConfigurationConstants.FILE_EXTENSION;
//Write JSON file
try (OutputStreamWriter file = new OutputStreamWriter(new FileOutputStream(fileLocation), StandardCharsets.UTF_8)) {
file.write(configJSON.toString());
file.flush();
file.close();
} catch (IOException e) {
e.printStackTrace();
}
URI uriSchemaLocation = new File(fileLocation).toURI();
ConfigParser configParser = new ConfigParser(uriSchemaLocation);
configParser.parseConfig(TestHelper.getMockedJSONObject(fileLocation));
}
Solution
This is the method that you intend to test, correct? I am surprised to see that it contains test code (configParser.parseConfig(TestHelper.getMockedJSONObject(fileLocation));
)...
What exactly do you want to test?
You could for example verify the content of the file that gets written by loading that file. However, that accounts only for a part of the method logic.
I don't see any
@Override
annotation and therefore assume that you are not overriding a method. You could change the method signature to return the parsed config and check it with assertions.There might be other ways to retrieve the configuration; this depends on the logic of
configParser.parseConfig(...)
.You could also consider extracting the last tree lines to another method and test that method.
To sum up, you can either change the method to return a result, or extract chunks to own methods and test these, or retrieve the result from another source (in case something like configParser.getParsedConfig()
exists).
Answered By - nrainer