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