我正在为一个接受参数id
的方法编写单元测试,如下所示:
public void searchid(String id) {
Document doc = Repository.findDocument(id); //returns a document
if (doc == null) {
System.out.println("id missing");
} else {
String stringRecord = doc.asJsonString(); //converting doc to string
这里Repository.findDocument(id)
返回一个文档。在我的单元测试中,我从src/test/resources
获取JSON文件。那么,我如何模拟Repository.findDocument(id)
,以便从我的资源中获取文件呢?
谢谢你,
2条答案
按热度按时间vhipe2zx1#
您可以尝试在单元测试方法中模拟
Repository.findDocument(id)
调用。这将在执行
Repository.findDocument(id)
调用时返回Mocked Document对象。jpfvwuh42#
可测试性的关键是你有一个字段
repository
,它被构造函数注入到你的类中。这样你就可以很容易地用一个假的示例(例如一个mockito mock)替换真实的仓库。据我所知,学习如何编写可测试代码的最佳资源是http://misko.hevery.com/code-reviewers-guide/
2023-09-18发布不幸的是,上述链接已断开。但我发现这里引用的大部分材料:
感兴趣的读者可以浏览https://www.google.com/search?q=site%3Atesting.googleblog.com%20misko%20hevery