簡體   English   中英

如何使用 void 返回類型為 function 編寫單元測試

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

我是編寫單元測試的新手。 我看到了幾個 jUnit 的例子,但它們都是用於返回值的函數。

我必須為以下方法編寫單元測試。 此外,我們在此方法中使用不屬於此 class 的對象和方法,例如 ConfigParser 和 ParseConfig。 我如何為此類方法編寫單元測試?

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

這是您打算測試的方法,對嗎? 我很驚訝地看到它包含測試代碼( configParser.parseConfig(TestHelper.getMockedJSONObject(fileLocation)); )...

你到底想測試什么?

  • 例如,您可以通過加載該文件來驗證寫入的文件的內容。 但是,這僅占方法邏輯的一部分。

  • 我沒有看到任何@Override注釋,因此假設您沒有覆蓋方法。 您可以更改方法簽名以返回已解析的配置並使用斷言進行檢查。

  • 可能還有其他方法可以檢索配置; 這取決於configParser.parseConfig(...)的邏輯。

  • 您還可以考慮將最后的樹線提取到另一種方法並測試該方法。

總而言之,您可以更改方法以返回結果,或者提取塊以擁有方法並測試這些方法,或者從另一個源檢索結果(以防存在configParser.getParsedConfig()類的東西)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM