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?
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