Debian Codegraph @

debian/go/src/github.com/prashantv/gostub/doc.go

raw
1 /*
2 Package gostub is used for stubbing variables in tests, and resetting the
3 original value once the test has been run.
4
5 This can be used to stub static variables as well as static functions. To
6 stub a static variable, use the Stub function:
7
8 var configFile = "config.json"
9
10 func GetConfig() ([]byte, error) {
11 return ioutil.ReadFile(configFile)
12 }
13
14 // Test code
15 stubs := gostub.Stub(&configFile, "/tmp/test.config")
16
17 data, err := GetConfig()
18 // data will now return contents of the /tmp/test.config file
19
20 gostub can also stub static functions in a test by using a variable
21 to reference the static function, and using that local variable to call
22 the static function:
23 var timeNow = time.Now
24
25 func GetDate() int {
26 return timeNow().Day()
27 }
28
29 You can test this by using gostub to stub the timeNow variable:
30 stubs := gostub.Stub(&timeNow, func() time.Time {
31 return time.Date(2015, 6, 1, 0, 0, 0, 0, time.UTC)
32 })
33 defer stubs.Reset()
34
35 // Test can check that GetDate returns 6
36
37 If you are stubbing a function to return a constant value like in
38 the above test, you can use StubFunc instead:
39 stubs := gostub.StubFunc(&timeNow, time.Date(2015, 6, 1, 0, 0, 0, 0, time.UTC))
40 defer stubs.Reset()
41
42 StubFunc can also be used to stub functions that return multiple values:
43 var osHostname = osHostname
44 // [...] production code using osHostname to call it.
45
46 // Test code:
47 stubs := gostub.StubFunc(&osHostname, "fakehost", nil)
48 defer stubs.Reset()
49
50 StubEnv can be used to setup environment variables for tests, and the environment
51 values are reset to their original values upon Reset:
52
53 stubs := gostub.New()
54 stubs.SetEnv("GOSTUB_VAR", "test_value")
55 defer stubs.Reset()
56
57 The Reset method should be deferred to run at the end of the test to reset
58 all stubbed variables back to their original values.
59
60 You can set up multiple stubs by calling Stub again:
61 stubs := gostub.Stub(&v1, 1)
62 stubs.Stub(&v2, 2)
63 defer stubs.Reset()
64
65 For simple cases where you are only setting up simple stubs, you can condense
66 the setup and cleanup into a single line:
67 defer gostub.Stub(&v1, 1).Stub(&v2, 2).Reset()
68 This sets up the stubs and then defers the Reset call.
69
70 You should keep the return argument from the Stub call if you need to change
71 stubs or add more stubs during test execution:
72 stubs := gostub.Stub(&v1, 1)
73 defer stubs.Reset()
74
75 // Do some testing
76 stubs.Stub(&v1, 5)
77
78 // More testing
79 stubs.Stub(&b2, 6)
80
81 The Stub call must be passed a pointer to the variable that should be stubbed,
82 and a value which can be assigned to the variable.
83 */
84 package gostub
85
86 // FIXME: godocdown no longer works with go syntax highlighting.
87 //go:generate godocdown -template README.md.tmpl --output=README.md