如何编写具有无效返回类型的函数的单元测试 [英] How do i write unit test for function with void return type
问题描述
我是编写单元测试的新手.我看到了几个jUnit的示例,但是它们都是用于返回值的函数的.
I am new to writing Unit tests. I saw few examples of jUnit , but they all were for functions returning a value.
我必须为以下方法编写单元测试.另外,我们在此方法中使用的对象和方法不属于此类,例如ConfigParser和ParseConfig.我该如何为这种方法编写单元测试?
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));
}
推荐答案
这是您要测试的方法,对吗?我很惊讶地看到它包含测试代码(configParser.parseConfig(TestHelper.getMockedJSONObject(fileLocation));
)...
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));
)...
您到底想测试什么?
-
例如,您可以通过加载文件来验证要写入的文件的内容.但是,这仅占方法逻辑的一部分.
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.
我没有看到任何@Override
批注,因此假定您没有覆盖方法.您可以更改方法签名以返回已解析的配置,并使用断言对其进行检查.
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.
可能还有其他方法可以检索配置;例如,这取决于configParser.parseConfig(...)
的逻辑.
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.
总而言之,您可以更改方法以返回结果,也可以提取块以拥有自己的方法并进行测试,或者从其他来源检索结果(如果存在类似configParser.getParsedConfig()
的情况).
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).
这篇关于如何编写具有无效返回类型的函数的单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!