-
-
Notifications
You must be signed in to change notification settings - Fork 247
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
What is the best way to mock carbon in unit testing? #195
Comments
oh nice thank you, I have a separate question say I was to inject carbon into a service struct i.e. func main() {
lang := carbon.NewLanguage()
lang.SetResources(map[string]string{
"before": "Expires in %s",
"after": "Expired %s ago",
})
c := carbon.SetLanguage(lang)
ms := services.NewMyService(&c)
diff := ms.FromNowHumanReadable(...)
} type MysServiceInterface interface {
FromNowHumanReadable(date time.time) string
}
type MyService struct {
c *carbon.Carbon
}
func NewMyService(c *carbon.Carbon) MysServiceInterface {
return &MyService{
c: c,
}
}
func (d *Date) FromNowHumanReadable(date time.Time) string {
endDate := d.carbon.CreateFromTimestamp(date.Unix())
return d.carbon.Now().DiffForHumans(endDate)
} In this scenario, i have a wrapper helper to always get the diff from now, how do I mock carbon in a case where I have a single language which will save having to append the language string each call. |
Language locale must be set when rewriting some translation resources,if rewriting all resources, it is not necessary. lang := carbon.NewLanguage()
lang.SetLocale("en")
lang.SetResources(map[string]string{
"before": "Expires in %s",
"after": "Expired %s ago",
}) |
I appreciate what you are saying here 👍 |
I appreciate what you are saying here 👍 |
I am testing a web service and trying to mock the time using .SetTestNow() but in the handler/controller the time is not mocked |
Show sample code. |
c := carbon.SetTimezone(carbon.UTC)
c.Now().ToDateString() // 2023-12-27
c.IsSetTestNow() // false
c.SetTestNow(carbon.Parse("2020-08-05"))
c.Now().ToDateString() // 2020-08-05
c.Now().IsSetTestNow() // true
c.UnSetTestNow()
c.Now().ToDateString() // 2023-12-2
c.Now().IsSetTestNow() // false |
I thought we could do globally without creating an object like
And wherever i called
It'll give 2020-12-12 |
Hi,
I'm wondering what the best way to mock carbon as I cannot see an interface to aid with testing a custom service.
Thanks,
The text was updated successfully, but these errors were encountered: