1
0

lazy_obj.go 622 B

1234567891011121314151617181920212223242526272829303132
  1. package testutil
  2. import (
  3. "testing"
  4. "github.com/stretchr/testify/require"
  5. )
  6. // LazyObj is a function that returns an object of type T.
  7. type LazyObj[T any] func() T
  8. // LazyObjInit is a function that initializes and returns an object of type T and an error if any.
  9. type LazyObjInit[T any] func() (T, error)
  10. // NewLazyObj creates a new LazyObj that initializes the object on the first call.
  11. func NewLazyObj[T any](t *testing.T, init LazyObjInit[T]) LazyObj[T] {
  12. t.Helper()
  13. var obj *T
  14. return func() T {
  15. if obj != nil {
  16. return *obj
  17. }
  18. o, err := init()
  19. require.NoError(t, err)
  20. obj = &o
  21. return o
  22. }
  23. }