如何在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
Run Code Online (Sandbox Code Playgroud)
同样对于文件输出,我会有类似以下内容:
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
Run Code Online (Sandbox Code Playgroud)
djd*_*jd0 14
您可以使用缓冲区.
通常,在代码中使用io.Reader和io.Writer接口(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")
}
Run Code Online (Sandbox Code Playgroud)
程序中的函数使用:
package main
import (
"mypkg"
"os"
)
func main() {
mypkg.MyFunction(os.Stdin, os.Stdout)
}
Run Code Online (Sandbox Code Playgroud)
测试:
// 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()
}
}
Run Code Online (Sandbox Code Playgroud)
如果您需要io.ReadSeeker,并且不需要写访问权限,请使用bytes.Reader:
import "bytes"
data := []byte("success")
readSeeker := bytes.NewReader(data)
Run Code Online (Sandbox Code Playgroud)
这对于诸如 之类的事情很有用http.ServeContent()。
或者,更简单地说:
import "bytes"
data := []byte("success")
readSeeker := bytes.NewReader(data)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7585 次 |
| 最近记录: |