一般来说,我是编写测试的新手。我需要测试的类有一个方法,需要测试:
public String run(final Map<String, Dataset> datasets)
throws ApiException {
final String sourcePath = ElementsUtil.getElementFromDatasets(inputElementNames.get(0), datasets).getValue();
final String destinationPath = ElementsUtil.getElementFromDatasets(inputElementNames.get(1), datasets).getValue();
final File source = new File(sourcePath);
final File destination = new File(destinationPath);
if (source.exists()) {
if (source.isDirectory()) {
final IOFileFilter filter = new WildcardFileFilter(pattern);
final Iterator<File> it = FileUtils.iterateFiles(source, filter, null);
while (it.hasNext()) {
final File file = it.next();
moveFileToDirectory(file, destination);
}
} else {
moveFileToDirectory(source, destination);
}
} else {
LOGGER.error("Source file/folder at path {} doesn't exist.", sourcePath);
}
return "0";
}
起初,由于我编写单元测试的知识有限,我的单元测试看起来像这样:
@Test(description = "Test in case the source is a file.")
public void moveFileTest1() {
// setup
final String fileName = UUID.randomUUID().toString() + ".txt";
final String folderName = UUID.randomUUID().toString();
final Element source = new Element("source", "./" + fileName);
final Element destination = new Element("destination", "./" + folderName);
...
final Path sourcePath = Paths.get(source.getValue());
final Path destinationPath = Paths.get(destination.getValue());
final Path fileDestination = Paths.get(destination.getValue() + "/" + fileName);
try {
Files.createFile(sourcePath);
Files.createDirectory(destinationPath);
// exercise
moveFile.run("", datasets, null);
// verify
Assert.assertEquals(Files.exists(fileDestination), true);
Assert.assertEquals(Files.exists(sourcePath), false);
} catch (ApiException | IOException e) {
LOGGER.error("Exception : ", e);
} finally {
// teardown
try {
Files.deleteIfExists(sourcePath);
} catch (final IOException e) {
LOGGER.error("Exception in teardown: ", e);
}
try {
Files.deleteIfExists(fileDestination);
} catch (IOException e) {
LOGGER.error("Exception in teardown: ", e);
}
try {
Files.deleteIfExists(destinationPath);
} catch (IOException e) {
LOGGER.error("Exception in teardown: ", e);
}
}
}
在阅读了一些关于单元测试的文章后,我发现我的测试并不能完全测试一个单元,因为我的方法依赖于不同的 util 方法。我还发现了有关在测试中模拟对象以及应该如何模拟所有内容的信息。我的问题是:我应该在这些 util 方法/新对象调用等中的每一个中使用模拟还是有不同的方法?您将如何测试这段代码?
最佳答案
您所做的称为集成测试。集成测试是在不模拟任何东西的情况下,在真实数据或测试本身产生的数据上测试对象/方法。集成测试的作用是测试您的单元、您的单元使用的单元和使用流程。如果您只想测试您的单元,您应该模拟您的单元使用的所有其他单元,并创建这些单元是否成功完成工作的流程。这意味着您应该复制一个测试,其中使用的单元抛出异常/返回一个您不期望的值作为一个好的值(仅当它真的可以做到时)并返回一个您期望的值以及现在如何工作和。 通常在编写测试时,你会同时进行两种测试,单元测试和集成测试
关于java - 在 java 中模拟静态方法编写单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36080522/