英文:
Write unit test for a method which need a file location
问题
我有一个方法,它以文件位置作为参数。
```Java
public void methodA(String fileLocation){
// 做一些操作
methodB(fileLocation);
}
private void methodB(String fileLocation){
readFile();
// 做一些操作
}
我想为 methodA()
编写一些单元测试。文件位置是一个指向 YAML 文件的位置,我需要为各种类型的 YAML 文件编写单元测试。由于 methodA
以文件路径作为参数,所以我无法将 YAML 文件直接传递为字符串。另外,由于 methodB
是私有的,我无法直接为 methodB
编写单元测试。
- 在这里违反了哪个软件工程原则?
- 如何重构此代码以便我可以编写如上所示的单元测试?
一开始我的计划是将 methodB
更新为以 YAML 字符串作为参数,并将其设为公有方法。但我不确定将完整的 YAML 字符串作为参数传递给方法是否是一个好的做法,因为对 methodB
的调用次数很多。
<details>
<summary>英文:</summary>
I have a method which take a file location as an argument.
```Java
public void methodA(String fileLocation){
// Do something
methodB(fileLocation);
}
private void methodB(String fileLocation){
readFile();
// Do Something
}
I want to write a number of unit test for methodA()
. The file location is a location to the YAML file and I need to write unit test for various type of YAML files. Since methodA
get a file path as the argument I can't pass the YAML file as a String. Also since the methofB
is private I can't directly write unit test for methodB
.
- What software engineer principal has been broken here?
- How I can refactor this code as I can write Unit test as above.
At the beginning my plan was to update methodB
as it take YAML string as an argument and make it public. But I am not sure is it a good practice to pass complete YAML string as a argument to a method since there are big number of calls to methodB
.
答案1
得分: 1
为什么要将YAML文件作为字符串传递?只需将测试文件上传到资源目录中,并使用它们来测试您的逻辑。其次,对于方法B,我个人会使用PowerMock的执行私有方法的功能,这里有一个简单的指南 - https://www.baeldung.com/powermock-private-method。一般来说,仅为了测试而改变方法的可见性是一种不好的做法,即使没有必要,也不要将方法B设置为公共的。
英文:
Why do you want to pass YAML file as a string? Just upload test files into your resources directory, and use them to test your logic. Secondly, for the method B, I would personally use PowerMock's ability to execute private method, here is a simple guide for that - https://www.baeldung.com/powermock-private-method. In general, it's a bad practice to change method's visibility just for sake of the tests, i.e. do not make methodB public if there is no necessity in it.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论