在Go语言中,如何测试大字符串长度的单元测试覆盖率?

huangapple go评论83阅读模式
英文:

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 &lt;&lt; 32

var ErrTooLarge = errors.New(&quot;String is too large!&quot;)

func Process(s string) error {
	if len(s) &gt; 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(&quot;123&quot;); err != nil {
		t.Errorf(&quot;Expected success, got: %v&quot;, err)
	}

	// Test failure (too large string)
	limit = 5
	if err := Process(&quot;123456&quot;); err != ErrTooLarge {
		t.Errorf(&quot;Expected ErrTooLarge, got: %v&quot;, err)
	}
}

Running go test -cover:

PASS
coverage: 100.0% of statements
ok      play    0.001s

huangapple
  • 本文由 发表于 2016年11月28日 20:01:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/40843808.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定