How do i write unit test for function with void return type

回眸只為那壹抹淺笑 提交于 2021-01-28 05:41:54

问题


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));
}

回答1:


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).



来源:https://stackoverflow.com/questions/62080899/how-do-i-write-unit-test-for-function-with-void-return-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!