Last modified by chrisby on 2023/10/18 18:17

From version 1.1
edited by chrisby
on 2023/06/17 14:18
Change comment: There is no comment for this version
To version 1.2
edited by chrisby
on 2023/06/17 14:19
Change comment: There is no comment for this version

Summary

Details

Page properties
Content
... ... @@ -20,6 +20,7 @@
20 20  
21 21  === Source Code ===
22 22  
23 +(% style="text-align: justify;" %)
23 23  First, we need the dependency we want to mock, for this example 'NameProvider.go':
24 24  
25 25  {{code language="go"}}
... ... @@ -39,8 +39,10 @@
39 39  go generate ./...
40 40  {{/code}}
41 41  
43 +(% style="text-align: justify;" %)
42 42  The 'mock_nameProvider.go' file should now be generated for the appropriate path and package.
43 43  
46 +(% style="text-align: justify;" %)
44 44  The unit to be tested, 'Greeter', is simple for the sake of an example. It has a dependency of type 'NameProvider' into which the mock object can be injected, and its method 'Greet()' adds a "Hello " before the name provided by the 'NameProvider'. The code for 'Greeter.go' is:
45 45  
46 46  {{code language="go"}}
... ... @@ -55,6 +55,7 @@
55 55  }
56 56  {{/code}}
57 57  
61 +(% style="text-align: justify;" %)
58 58  Finally, here is the test code from 'Greeter_test.go':
59 59  
60 60  {{code}}
... ... @@ -80,6 +80,7 @@
80 80  }
81 81  {{/code}}
82 82  
87 +(% style="text-align: justify;" %)
83 83  The first four lines of the test are just to create the mock object and inject it into 'greeter'. Next, the mock can be instructed to behave in a specific way appropriate to the test case, i.e. to simply return "john" when "ProvideName()" is called. Note that the test calls the 'NewMockNameProvider()' method directly from the 'mock_nameProvider.go' file.
84 84  
85 85  === ===
... ... @@ -90,10 +90,11 @@
90 90  go test ./...
91 91  {{/code}}
92 92  
93 -=== ===
98 +=== ===
94 94  
95 95  === Ignore Mock Files in Git ===
96 96  
102 +(% style="text-align: justify;" %)
97 97  Generated code should not be part of the git history, and should therefore be ignored. Using the mock naming convention from above, a corresponding entry in the '.gitignore' file could be:
98 98  
99 99  {{code}}