【发布时间】:2020-05-29 07:34:18
【问题描述】:
我是编写单元测试的新手。我看到了几个 jUnit 的例子,但它们都是用于返回值的函数。
我必须为以下方法编写单元测试。此外,我们在此方法中使用不属于此类的对象和方法,例如 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));
}
【问题讨论】:
-
如果你编写单元测试,你应该考虑你想测试什么。在这种情况下,将写入一个文件。那么也许您想调用该方法并检查单元测试中的文件内容?如果您在测试中使用不想测试的对象,则可以使用 Mockito 之类的模拟框架。
标签: java unit-testing spring-mvc junit mockito