英文:
Unit test coverage with huge string length in Go?
问题
在我的一些代码中,我有一个测试,确保字符串的长度小于2^32
。但是由于生成一个更大的字符串进行测试可能会导致测试程序崩溃并出现内存错误,所以很难进行测试。
我该如何实现100%的测试覆盖率,同时又能安全地测试这种情况?
英文:
In some code I have a test ensuring that a string length is smaller than 2^32
. But it is difficult to test since generating a bigger string for testing would probably crash the test program with an out of memory error.
How may I achieve 100% test coverage but still testing for such case just to be safe?
答案1
得分: 3
重构你的代码,将限制值移到可以被测试更改的函数之外:
var limit = 1 << 32
var ErrTooLarge = errors.New("字符串太长!")
func Process(s string) error {
if len(s) > limit {
return ErrTooLarge
}
// 一切正常
return nil
}
进行测试:
func TestProcess(t *testing.T) {
// 保存限制值并在最后恢复:
old := limit
defer func() { limit = old }()
// 测试成功情况
if err := Process("123"); err != nil {
t.Errorf("期望成功,实际得到:%v", err)
}
// 测试失败情况(字符串太长)
limit = 5
if err := Process("123456"); err != ErrTooLarge {
t.Errorf("期望 ErrTooLarge,实际得到:%v", err)
}
}
运行 go test -cover
:
PASS
coverage: 100.0% of statements
ok play 0.001s
英文:
Refactor your code, move the limit outside of your function which tests can change:
var limit = 1 << 32
var ErrTooLarge = errors.New("String is too large!")
func Process(s string) error {
if len(s) > limit {
return ErrTooLarge
}
// All OK
return nil
}
Testing it:
func TestProcess(t *testing.T) {
// Save limit and restore it at the end:
old := limit
defer func() { limit = old }()
// Test success
if err := Process("123"); err != nil {
t.Errorf("Expected success, got: %v", err)
}
// Test failure (too large string)
limit = 5
if err := Process("123456"); err != ErrTooLarge {
t.Errorf("Expected ErrTooLarge, got: %v", err)
}
}
Running go test -cover
:
PASS
coverage: 100.0% of statements
ok play 0.001s
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论