Skip to content

Instantly share code, notes, and snippets.

@matope
Created August 14, 2014 01:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matope/7a88d2123d49bc64b88b to your computer and use it in GitHub Desktop.
Save matope/7a88d2123d49bc64b88b to your computer and use it in GitHub Desktop.
Go Stubbing
package main
import (
"fmt"
"time"
)
func main() {
fmt.Println(Greet("マトペ"))
}
func Greet(n string) string {
t := time.Now()
if 6 <= t.Hour() && t.Hour() <= 18 {
return fmt.Sprintf("こんにちは%sさん。今は%d時ですよ!", n, t.Hour())
} else {
return fmt.Sprintf("こんばんは%sさん。今は%d時ですよ!", n, t.Hour())
}
}
func Greet(n string, t time.Time) string {
if 6 <= t.Hour() && t.Hour() <= 18 {
return fmt.Sprintf("こんにちは%sさん。今は%d時ですよ!", n, t.Hour())
} else {
return fmt.Sprintf("こんばんは%sさん。今は%d時ですよ!", n, t.Hour())
}
}
package main
import (
"fmt"
"time"
)
var timeNowFunc = time.Now
func main() {
fmt.Println(Greet("マトペ"))
}
func Greet(n string) string {
t := timeNowFunc()
if 6 <= t.Hour() && t.Hour() <= 18 {
return fmt.Sprintf("こんにちは%sさん。今は%d時ですよ!", n, t.Hour())
} else {
return fmt.Sprintf("こんばんは%sさん。今は%d時ですよ!", n, t.Hour())
}
}
package main
import (
"testing"
"time"
)
const timeformat = "2006-01-02 15:04:06" // timeのフォーマット指定文字列
func setNow(t time.Time) {
timeNowFunc = func() time.Time { return t }
}
func TestMain(t *testing.T) {
evening, _ := time.Parse(timeformat, "2014-08-14 14:10:00")
night, _ := time.Parse(timeformat, "2014-08-14 22:30:00")
// 昼のテスト
setNow(evening)
if ret := Greet("まとぺ"); ret != "こんにちはまとぺさん。今は14時ですよ!" {
t.Errorf("Greet Fails. Got [%s]\n", ret)
}
// 夜のテスト
setNow(night)
if ret := Greet("まとぺ"); ret != "こんばんはまとぺさん。今は22時ですよ!" {
t.Errorf("Greet Fails. Got [%s]\n", ret)
}
}
package main
import (
"fmt"
"time"
)
var _time = struct {
Now func() time.Time
Since func(time.Time) time.Duration
}{
time.Now,
time.Since,
}
func main() {
fmt.Println(_time.Now())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment