Skip to main content
Active reading.
Source Link
Peter Mortensen
  • 31.6k
  • 22
  • 109
  • 133

Also if you need to just stub time.Now you can inject the dependency as a function, e.g.,

func moonPhase(now func() time.Time) {
  if now == nil {
    now = time.Now
  }

  // useUse now()...
}

// Then dependent code uses just
moonPhase(nil)

// And tests inject own version
stubNow := func() time.Time { return time.Unix(1515151515, 0) }
moonPhase(stubNow)

Granted, all that is a bit ugly if you come from a dynamic languages background (e.g., Ruby) :(

Also if you need to just stub time.Now you can inject dependency as a function, e.g.

func moonPhase(now func() time.Time) {
  if now == nil {
    now = time.Now
  }

  // use now()...
}

// Then dependent code uses just
moonPhase(nil)

// And tests inject own version
stubNow := func() time.Time { return time.Unix(1515151515, 0) }
moonPhase(stubNow)

Granted all that is a bit ugly if you come from dynamic languages background (e.g. Ruby) :(

Also if you need to just stub time.Now you can inject the dependency as a function, e.g.,

func moonPhase(now func() time.Time) {
  if now == nil {
    now = time.Now
  }

  // Use now()...
}

// Then dependent code uses just
moonPhase(nil)

// And tests inject own version
stubNow := func() time.Time { return time.Unix(1515151515, 0) }
moonPhase(stubNow)

Granted, all that is a bit ugly if you come from a dynamic languages background (e.g., Ruby) :(

Source Link
Ev Dolzhenko
  • 6.2k
  • 6
  • 39
  • 30

Also if you need to just stub time.Now you can inject dependency as a function, e.g.

func moonPhase(now func() time.Time) {
  if now == nil {
    now = time.Now
  }

  // use now()...
}

// Then dependent code uses just
moonPhase(nil)

// And tests inject own version
stubNow := func() time.Time { return time.Unix(1515151515, 0) }
moonPhase(stubNow)

Granted all that is a bit ugly if you come from dynamic languages background (e.g. Ruby) :(