【发布时间】:2018-11-05 15:26:49
【问题描述】:
提前道歉 - 我知道这已经被问了一千次了,但我浏览了这么多文章/文档,我真是迷路了。
我有一个类,它接收一个 XML 文件,然后使用 DocumentBuilder 将其解析为一个新文件,该文件将用作其他类使用的源。
我需要测试我的方法(这是无效的)。我的项目已经完成,但我需要测试。
如果有人好心告诉我如何做到这一点,我可以继续对我的其他类遵循相同的逻辑,因为我项目中 90% 的方法不会返回任何内容。
谢谢...
public class XmlToCsv {
public static void xmlToCsv(String sourceXlsFile, String sourceCsvFile, String sourceXmlFile) throws Exception {
//define the files
File stylesheet = new File(sourceXlsFile);
File xmlSource = new File(sourceXmlFile);
//create the DocumentBuilder to parse the XML file
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(xmlSource);
//input the stylesheet to transform the XML to
StreamSource stylesource = new StreamSource(stylesheet);
Transformer transformer = TransformerFactory.newInstance().newTransformer(stylesource);
//write a new output file using the stylesheet format
Source source = new DOMSource(document);
Result outputTarget = new StreamResult(new File(sourceCsvFile));
transformer.transform(source, outputTarget);
}
}
【问题讨论】:
-
被测方法不返回任何内容的事实无关紧要。测试是通过查看调用的可观察效果并对其进行断言来执行的。无论是通过返回值还是通过修改其他内容来完成这些效果都会对测试有所改变,但逻辑几乎相同。
-
这很奇怪。可以发誓测试 void/non-void 方法是两个不同的实体。
-
不是真的,代码会有些不同,但整体流程是一样的。您不是针对返回值进行断言,而是针对某些副作用(或除此之外)进行断言。这些可能是参数对象的状态、一些全局状态、文件系统或数据库更改,或者其他任何东西,具体取决于方法的作用。返回值只是方法可以做的事情之一,但不是唯一的。
-
我明白了。那么我对这个类的测试方法是 asserting 正在创建一个文件。这是我的副作用。仍然不确定如何将其格式化为 dbfactory 和流/变压器
标签: java unit-testing testing junit mockito