如何在 Go 中创建用于单元测试的内存文件?
在 Python 中,我测试使用 io.BytesIO
读取文件或写入文件或 io.StringIO
.例如,要测试文件解析器,我会
def test_parse_function():
infile = io.StringIO('''\
line1
line2
line3
''')
parsed_contents = parse_function(infile)
expected_contents = ['line1', 'line2', 'line3'] # or whatever is appropriate
assert parsed_contents == expected_contents
与文件输出类似,我会有如下内容:
def test_write_function():
outfile = io.StringIO()
write_function(outfile, ['line1', 'line2', 'line3'])
outfile.seek(0)
output = outfile.read()
expected_output = '''\
line1
line2
line3
'''
assert output == expected_output
最佳答案
您可以使用 Buffer .
一般来说,使用io.Reader 是个好主意和 io.Writer代码中的接口(interface)(Buffer 实现两者)来处理 IO。这样你就可以用同样的方式处理各种输入/输出方法(本地文件、内存缓冲区、网络连接......),而不知道你在使用的特定函数中处理的是什么。它使它更加抽象并使测试变得微不足道。
简单函数的使用示例:
函数定义:
// mypkg project mypkg.go
package mypkg
import (
"bufio"
"io"
"strings"
)
func MyFunction(in io.Reader, out io.Writer) {
rd := bufio.NewReader(in)
str, _ := rd.ReadString('\n')
io.WriteString(out, strings.TrimSuffix(str, "\n")+" was input\n")
}
程序中的函数使用:
package main
import (
"mypkg"
"os"
)
func main() {
mypkg.MyFunction(os.Stdin, os.Stdout)
}
测试:
// mypkg project mypkg_test.go
package mypkg
import (
"bytes"
"testing"
)
func TestMyFunction(t *testing.T) {
ibuf := bytes.NewBufferString("hello\n")
obuf := bytes.NewBufferString("")
MyFunction(ibuf, obuf)
if obuf.String() != "hello was input\n" {
t.Fail()
}
}
关于unit-testing - 用于测试的内存文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40316052/