Changes for page Quickstart: 'mockgen' Mocking Library
Last modified by chrisby on 2023/10/18 18:17
Summary
-
Page properties (1 modified, 0 added, 0 removed)
Details
- Page properties
-
- Content
-
... ... @@ -20,7 +20,6 @@ 20 20 21 21 === Source Code === 22 22 23 -(% style="text-align: justify;" %) 24 24 First, we need the dependency we want to mock, for this example 'NameProvider.go': 25 25 26 26 {{code language="go"}} ... ... @@ -40,10 +40,8 @@ 40 40 go generate ./... 41 41 {{/code}} 42 42 43 -(% style="text-align: justify;" %) 44 44 The 'mock_nameProvider.go' file should now be generated for the appropriate path and package. 45 45 46 -(% style="text-align: justify;" %) 47 47 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: 48 48 49 49 {{code language="go"}} ... ... @@ -58,7 +58,6 @@ 58 58 } 59 59 {{/code}} 60 60 61 -(% style="text-align: justify;" %) 62 62 Finally, here is the test code from 'Greeter_test.go': 63 63 64 64 {{code}} ... ... @@ -84,7 +84,6 @@ 84 84 } 85 85 {{/code}} 86 86 87 -(% style="text-align: justify;" %) 88 88 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. 89 89 90 90 === === ... ... @@ -95,11 +95,10 @@ 95 95 go test ./... 96 96 {{/code}} 97 97 98 -=== === 93 +=== === 99 99 100 100 === Ignore Mock Files in Git === 101 101 102 -(% style="text-align: justify;" %) 103 103 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: 104 104 105 105 {{code}}