我正在训练 TDD 方法,但我有一个问题。如何测试 IO 操作?到目前为止,我使用的是 junit,但我读到它不应该用于测试外部源(数据库、文件......),那么什么会更好?对不起,我的英语不好
2 回答
You can't test the internal working of those external sources, but you can check the results.
For example, writing to a file:
Start test
Store data you want to write in a variable
Write data to file
Read file
Check if data is the same as the one you stored
End test
Testing is about verifying end results, so it's not necessarily a bad thing you "lose" sight of a part of the process. Generally you can assume external sources (libraries, IO..) are well tested.
更改要传递的 APIInputStream
和/或OutputStream
让 jUnit 代码传递 ByteArrayInputStream 和ByteArrayOutputStream
,您可以轻松地设置/读取它们。
当然,您的生产代码需要更改为,但您通常可以通过简单的重构来实现;保留 API 原样,但让公共方法调用重构的方法,例如:
改变
public void read(File file) {
// do something with contents of file
}
至
public void read(File file) {
read(new FileInputStream(file));
}
// test this method
public void read(InputStream inputStream) {
// do something with contents of inputStream
}