├── .gitignore ├── images ├── logo.pdf └── logo.png ├── go.mod ├── .travis.yml ├── helpers.go ├── interaction_validator.go ├── interaction_validator_test.go ├── moka_suite_test.go ├── go.sum ├── double.go ├── syntax.go ├── moka_test.go ├── double_test.go ├── interaction.go ├── README.md ├── LICENSE └── interaction_test.go /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | vendor/ 3 | *.coverprofile 4 | -------------------------------------------------------------------------------- /images/logo.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gcapizzi/moka/HEAD/images/logo.pdf -------------------------------------------------------------------------------- /images/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gcapizzi/moka/HEAD/images/logo.png -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/gcapizzi/moka 2 | 3 | go 1.12 4 | 5 | require ( 6 | github.com/onsi/ginkgo v1.8.0 7 | github.com/onsi/gomega v1.5.0 8 | ) 9 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | 3 | go: 4 | - master 5 | - 1.9.x 6 | - 1.8.x 7 | 8 | install: 9 | - go get -v -t ./... 10 | - go get github.com/onsi/gomega 11 | - go install github.com/onsi/ginkgo/ginkgo 12 | - export PATH=$PATH:$GOPATH/bin 13 | 14 | script: ginkgo -r --randomizeAllSpecs --randomizeSuites --failOnPending --trace --race --compilers=2 15 | -------------------------------------------------------------------------------- /helpers.go: -------------------------------------------------------------------------------- 1 | package moka 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | ) 7 | 8 | func formatMethodCall(methodName string, args []interface{}) string { 9 | stringArgs := []string{} 10 | for _, arg := range args { 11 | stringArgs = append(stringArgs, fmt.Sprintf("%#v", arg)) 12 | } 13 | 14 | return fmt.Sprintf("%s(%s)", methodName, strings.Join(stringArgs, ", ")) 15 | } 16 | -------------------------------------------------------------------------------- /interaction_validator.go: -------------------------------------------------------------------------------- 1 | package moka 2 | 3 | import "reflect" 4 | 5 | type interactionValidator interface { 6 | validate(interaction interaction) error 7 | } 8 | 9 | type typeInteractionValidator struct { 10 | t reflect.Type 11 | } 12 | 13 | func newTypeInteractionValidator(t reflect.Type) typeInteractionValidator { 14 | return typeInteractionValidator{t: t} 15 | } 16 | 17 | func (v typeInteractionValidator) validate(interaction interaction) error { 18 | return interaction.checkType(v.t) 19 | } 20 | 21 | type nullInteractionValidator struct{} 22 | 23 | func newNullInteractionValidator() nullInteractionValidator { 24 | return nullInteractionValidator{} 25 | } 26 | 27 | func (v nullInteractionValidator) validate(interaction interaction) error { 28 | return nil 29 | } 30 | -------------------------------------------------------------------------------- /interaction_validator_test.go: -------------------------------------------------------------------------------- 1 | package moka 2 | 3 | import ( 4 | "errors" 5 | "reflect" 6 | 7 | . "github.com/onsi/ginkgo" 8 | . "github.com/onsi/gomega" 9 | ) 10 | 11 | var _ = Describe("InteractionValidator", func() { 12 | Describe("NullInteractionValidator", func() { 13 | var nullInteractionValidator nullInteractionValidator 14 | 15 | BeforeEach(func() { 16 | nullInteractionValidator = newNullInteractionValidator() 17 | }) 18 | 19 | It("never returns an error", func() { 20 | Expect(nullInteractionValidator.validate(nil)).To(BeNil()) 21 | Expect(nullInteractionValidator.validate(newFakeInteraction(nil, false, nil, nil))).To(BeNil()) 22 | }) 23 | }) 24 | 25 | Describe("TypeInteractionValidator", func() { 26 | var fakeInteraction *fakeInteraction 27 | var typeInteractionValidator typeInteractionValidator 28 | 29 | BeforeEach(func() { 30 | fakeInteraction = newFakeInteraction(nil, false, nil, errors.New("CheckType failed")) 31 | typeInteractionValidator = newTypeInteractionValidator(reflect.TypeOf(someType{})) 32 | }) 33 | 34 | It("checks the interaction against the type", func() { 35 | err := typeInteractionValidator.validate(fakeInteraction) 36 | 37 | Expect(err).To(MatchError("CheckType failed")) 38 | Expect(fakeInteraction.checkTypeCalled).To(BeTrue()) 39 | Expect(fakeInteraction.receivedType).To(Equal(reflect.TypeOf(someType{}))) 40 | }) 41 | }) 42 | }) 43 | 44 | type someType struct{} 45 | -------------------------------------------------------------------------------- /moka_suite_test.go: -------------------------------------------------------------------------------- 1 | package moka 2 | 3 | import ( 4 | "reflect" 5 | 6 | . "github.com/onsi/ginkgo" 7 | . "github.com/onsi/gomega" 8 | 9 | "testing" 10 | ) 11 | 12 | func TestMoka(t *testing.T) { 13 | RegisterFailHandler(Fail) 14 | RunSpecs(t, "Moka Suite") 15 | } 16 | 17 | type fakeInteraction struct { 18 | callCalled bool 19 | receivedMethodName string 20 | receivedArgs []interface{} 21 | returnValues []interface{} 22 | matches bool 23 | verifyCalled bool 24 | verifyError error 25 | checkTypeCalled bool 26 | receivedType reflect.Type 27 | checkTypeError error 28 | } 29 | 30 | func newFakeInteraction(returnValues []interface{}, matches bool, verifyError error, checkTypeError error) *fakeInteraction { 31 | return &fakeInteraction{returnValues: returnValues, matches: matches, verifyError: verifyError, checkTypeError: checkTypeError} 32 | } 33 | 34 | func (i *fakeInteraction) call(methodName string, args []interface{}) ([]interface{}, bool) { 35 | i.callCalled = true 36 | i.receivedMethodName = methodName 37 | i.receivedArgs = args 38 | return i.returnValues, i.matches 39 | } 40 | 41 | func (i *fakeInteraction) verify() error { 42 | i.verifyCalled = true 43 | return i.verifyError 44 | } 45 | 46 | func (i *fakeInteraction) checkType(t reflect.Type) error { 47 | i.checkTypeCalled = true 48 | i.receivedType = t 49 | return i.checkTypeError 50 | } 51 | 52 | func (i *fakeInteraction) String() string { 53 | return "" 54 | } 55 | 56 | type fakeInteractionValidator struct { 57 | validationError error 58 | } 59 | 60 | func newFakeInteractionValidator(validationError error) fakeInteractionValidator { 61 | return fakeInteractionValidator{validationError: validationError} 62 | } 63 | 64 | func (v fakeInteractionValidator) validate(interaction interaction) error { 65 | return v.validationError 66 | } 67 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= 2 | github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= 3 | github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI= 4 | github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= 5 | github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= 6 | github.com/onsi/ginkgo v1.8.0 h1:VkHVNpR4iVnU8XQR6DBm8BqYjN7CRzw+xKUbVVbbW9w= 7 | github.com/onsi/ginkgo v1.8.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= 8 | github.com/onsi/gomega v1.5.0 h1:izbySO9zDPmjJ8rDjLvkA2zJHIo+HkYXHnf7eN7SSyo= 9 | github.com/onsi/gomega v1.5.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= 10 | golang.org/x/net v0.0.0-20180906233101-161cd47e91fd h1:nTDtHvHSdCn1m6ITfMRqtOd/9+7a3s8RBNOZ3eYZzJA= 11 | golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 12 | golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 13 | golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e h1:o3PsSEY8E4eXWkXrIP9YJALUkVZqzHJT5DOasTyn8Vs= 14 | golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 15 | golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= 16 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 17 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 18 | gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4= 19 | gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= 20 | gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= 21 | gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= 22 | gopkg.in/yaml.v2 v2.2.1 h1:mUhvW9EsL+naU5Q3cakzfE91YhliOondGd6ZrsDBHQE= 23 | gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 24 | -------------------------------------------------------------------------------- /double.go: -------------------------------------------------------------------------------- 1 | package moka 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "reflect" 7 | ) 8 | 9 | // Double is the interface implemented by all Moka double types. 10 | type Double interface { 11 | addInteraction(interaction interaction) 12 | Call(methodName string, args ...interface{}) ([]interface{}, error) 13 | verifyInteractions() 14 | } 15 | 16 | // StrictDouble is a strict implementation of the Double interface. 17 | // Any invocation of the `Call` method that won't match any of the configured 18 | // interactions will trigger a test failure and return an error. 19 | type StrictDouble struct { 20 | interactions []interaction 21 | interactionValidator interactionValidator 22 | failHandler FailHandler 23 | } 24 | 25 | // NewStrictDouble instantiates a new `StrictDouble`, using the global fail 26 | // handler and no validation on the configured interactions. 27 | func NewStrictDouble() *StrictDouble { 28 | return newStrictDoubleWithInteractionValidatorAndFailHandler( 29 | newNullInteractionValidator(), 30 | globalFailHandler, 31 | ) 32 | } 33 | 34 | // NewStrictDoubleWithTypeOf instantiates a new `StrictDouble`, using the 35 | // global fail handler and validating that any configured interaction matches 36 | // the specified type. 37 | func NewStrictDoubleWithTypeOf(value interface{}) *StrictDouble { 38 | return newStrictDoubleWithInteractionValidatorAndFailHandler( 39 | newTypeInteractionValidator(reflect.TypeOf(value)), 40 | globalFailHandler, 41 | ) 42 | } 43 | 44 | func newStrictDoubleWithInteractionValidatorAndFailHandler(interactionValidator interactionValidator, failHandler FailHandler) *StrictDouble { 45 | if failHandler == nil { 46 | panic("You are trying to instantiate a double, but Moka's fail handler is nil.\n" + 47 | "If you're using Ginkgo, make sure you instantiate your doubles in a BeforeEach(), JustBeforeEach() or It() block.\n" + 48 | "Alternatively, you may have forgotten to register a fail handler with RegisterDoublesFailHandler().") 49 | } 50 | 51 | return &StrictDouble{ 52 | interactions: []interaction{}, 53 | interactionValidator: interactionValidator, 54 | failHandler: failHandler, 55 | } 56 | } 57 | 58 | // Call performs a method call on the double. If a matching interaction is 59 | // found, its return values will be returned. If no configured interaction 60 | // matches, an error will be returned. 61 | func (d *StrictDouble) Call(methodName string, args ...interface{}) ([]interface{}, error) { 62 | for _, interaction := range d.interactions { 63 | interactionReturnValues, interactionMatches := interaction.call(methodName, args) 64 | if interactionMatches { 65 | return interactionReturnValues, nil 66 | } 67 | } 68 | 69 | errorMessage := fmt.Sprintf("Unexpected interaction: %s", formatMethodCall(methodName, args)) 70 | d.fail(errorMessage) 71 | return nil, errors.New(errorMessage) 72 | } 73 | 74 | func (d *StrictDouble) addInteraction(interaction interaction) { 75 | validationError := d.interactionValidator.validate(interaction) 76 | 77 | if validationError != nil { 78 | d.fail(validationError.Error()) 79 | return 80 | } 81 | 82 | d.interactions = append(d.interactions, interaction) 83 | } 84 | 85 | func (d *StrictDouble) verifyInteractions() { 86 | for _, interaction := range d.interactions { 87 | err := interaction.verify() 88 | if err != nil { 89 | d.fail(err.Error()) 90 | return 91 | } 92 | } 93 | } 94 | 95 | func (d *StrictDouble) fail(message string) { 96 | d.failHandler(message, 4) 97 | } 98 | -------------------------------------------------------------------------------- /syntax.go: -------------------------------------------------------------------------------- 1 | // Package moka provides a mocking framework for the Go programming language. 2 | // Moka works very well with the Ginkgo testing framework, but can be easily 3 | // used with any other testing framework, including the testing package from 4 | // the standard library. 5 | package moka 6 | 7 | // FailHandler is the type required for Moka fail handler functions. It matches 8 | // the type of the Ginkgo `Fail` function. 9 | type FailHandler func(message string, callerSkip ...int) 10 | 11 | var globalFailHandler FailHandler 12 | 13 | // RegisterDoublesFailHandler registers a function as the global fail handler 14 | // used by newly instantiated Moka doubles. 15 | func RegisterDoublesFailHandler(failHandler FailHandler) { 16 | globalFailHandler = failHandler 17 | } 18 | 19 | // AllowanceTarget wraps a Double to enable the configuration of allowed 20 | // interactions on it. 21 | type AllowanceTarget struct { 22 | double Double 23 | } 24 | 25 | // AllowDouble wraps a Double in an `AllowanceTarget`. 26 | func AllowDouble(double Double) AllowanceTarget { 27 | return AllowanceTarget{double: double} 28 | } 29 | 30 | // To configures the interaction built by the provided `InteractionBuilder` on 31 | // the wrapped `Double`. 32 | func (t AllowanceTarget) To(interactionBuilder InteractionBuilder) { 33 | t.double.addInteraction(interactionBuilder.build()) 34 | } 35 | 36 | // ExpectationTarget wraps a Double to enable the configuration of expected 37 | // interactions on it. 38 | type ExpectationTarget struct { 39 | double Double 40 | } 41 | 42 | // ExpectDouble wraps a Double in an `ExpectationTarget`. 43 | func ExpectDouble(double Double) ExpectationTarget { 44 | return ExpectationTarget{double: double} 45 | } 46 | 47 | // To configures the interaction built by the provided `InteractionBuilder` on 48 | // the wrapped `Double`. 49 | func (t ExpectationTarget) To(interactionBuilder InteractionBuilder) { 50 | t.double.addInteraction(newExpectedInteraction(interactionBuilder.build())) 51 | } 52 | 53 | // VerifyCalls verifies that all expected interactions on the wrapper `Double` 54 | // have actually happened. 55 | func VerifyCalls(double Double) { 56 | double.verifyInteractions() 57 | } 58 | 59 | // InteractionBuilder provides a fluid interface to build interactions to 60 | // configure on a `Double` 61 | type InteractionBuilder interface { 62 | build() interaction 63 | } 64 | 65 | // MethodInteractionBuilder allows to build interactions that are specific to a 66 | // method. It turns into more specific builders through the fluid interface 67 | // methods. 68 | type MethodInteractionBuilder struct { 69 | methodName string 70 | } 71 | 72 | // ReceiveCallTo allows to specify the method name of the interaction. 73 | func ReceiveCallTo(methodName string) MethodInteractionBuilder { 74 | return MethodInteractionBuilder{methodName: methodName} 75 | } 76 | 77 | // With allows to specify the expected arguments of the interaction. 78 | func (b MethodInteractionBuilder) With(args ...interface{}) ArgsInteractionBuilder { 79 | return ArgsInteractionBuilder{methodName: b.methodName, args: args} 80 | } 81 | 82 | // AndReturn allows to specify the return value of the interaction. 83 | func (b MethodInteractionBuilder) AndReturn(returnValues ...interface{}) ArgsInteractionBuilder { 84 | return ArgsInteractionBuilder{methodName: b.methodName, returnValues: returnValues} 85 | } 86 | 87 | // AndDo allows to specify a custom body to be executed by the interaction. 88 | func (b MethodInteractionBuilder) AndDo(body interface{}) BodyInteractionBuilder { 89 | return BodyInteractionBuilder{methodName: b.methodName, body: body} 90 | } 91 | 92 | func (b MethodInteractionBuilder) build() interaction { 93 | return newArgsInteraction(b.methodName, nil, nil) 94 | } 95 | 96 | // ArgsInteractionBuilder allows to build interactions that are defined by a 97 | // method name, a list of arguments and a list of return values 98 | type ArgsInteractionBuilder struct { 99 | methodName string 100 | args []interface{} 101 | returnValues []interface{} 102 | } 103 | 104 | // AndReturn allows to specify the return value of the interaction. 105 | func (b ArgsInteractionBuilder) AndReturn(returnValues ...interface{}) ArgsInteractionBuilder { 106 | return ArgsInteractionBuilder{methodName: b.methodName, args: b.args, returnValues: returnValues} 107 | } 108 | 109 | func (b ArgsInteractionBuilder) build() interaction { 110 | return newArgsInteraction(b.methodName, b.args, b.returnValues) 111 | } 112 | 113 | // BodyInteractionBuilder allows to build interactions that are defined by a 114 | // method name and a custom body 115 | type BodyInteractionBuilder struct { 116 | methodName string 117 | body interface{} 118 | } 119 | 120 | func (b BodyInteractionBuilder) build() interaction { 121 | return newBodyInteraction(b.methodName, b.body) 122 | } 123 | -------------------------------------------------------------------------------- /moka_test.go: -------------------------------------------------------------------------------- 1 | package moka 2 | 3 | import ( 4 | . "github.com/onsi/ginkgo" 5 | . "github.com/onsi/gomega" 6 | ) 7 | 8 | var _ = Describe("Moka", func() { 9 | var collaborator CollaboratorDouble 10 | var subject Subject 11 | 12 | var failHandlerCalled bool 13 | var failHandlerMessage string 14 | 15 | BeforeEach(func() { 16 | failHandlerCalled = false 17 | failHandlerMessage = "" 18 | RegisterDoublesFailHandler(func(message string, _ ...int) { 19 | failHandlerCalled = true 20 | failHandlerMessage = message 21 | }) 22 | 23 | collaborator = NewCollaboratorDouble() 24 | subject = NewSubject(collaborator) 25 | }) 26 | 27 | It("supports allowing a method call on a double", func() { 28 | AllowDouble(collaborator).To(ReceiveCallTo("Query").With("arg").AndReturn("result")) 29 | 30 | Expect(failHandlerCalled).To(BeFalse(), failHandlerMessage) 31 | 32 | result := subject.DelegateQuery("arg") 33 | 34 | Expect(failHandlerCalled).To(BeFalse(), failHandlerMessage) 35 | Expect(result).To(Equal("result")) 36 | }) 37 | 38 | It("makes tests fail on unexpected interactions", func() { 39 | collaborator.Query("unexpected") 40 | 41 | Expect(failHandlerCalled).To(BeTrue()) 42 | Expect(failHandlerMessage).To(Equal("Unexpected interaction: Query(\"unexpected\")")) 43 | }) 44 | 45 | It("supports expecting a method call on a double", func() { 46 | ExpectDouble(collaborator).To(ReceiveCallTo("Command").With("arg").AndReturn("result", nil)) 47 | 48 | Expect(failHandlerCalled).To(BeFalse(), failHandlerMessage) 49 | 50 | result, _ := subject.DelegateCommand("arg") 51 | 52 | Expect(result).To(Equal("result")) 53 | 54 | VerifyCalls(collaborator) 55 | 56 | Expect(failHandlerCalled).To(BeFalse(), failHandlerMessage) 57 | }) 58 | 59 | It("supports allowing a method call on a double without specifying any args", func() { 60 | AllowDouble(collaborator).To(ReceiveCallTo("Query").AndReturn("result")) 61 | 62 | Expect(failHandlerCalled).To(BeFalse(), failHandlerMessage) 63 | 64 | result := subject.DelegateQuery("anything") 65 | 66 | Expect(failHandlerCalled).To(BeFalse(), failHandlerMessage) 67 | Expect(result).To(Equal("result")) 68 | }) 69 | 70 | It("supports expecting a method call on a double without specifying any args or return values", func() { 71 | ExpectDouble(collaborator).To(ReceiveCallTo("CommandWithNoReturnValues")) 72 | 73 | Expect(failHandlerCalled).To(BeFalse(), failHandlerMessage) 74 | 75 | subject.DelegateCommandWithNoReturnValues("arg") 76 | VerifyCalls(collaborator) 77 | 78 | Expect(failHandlerCalled).To(BeFalse(), failHandlerMessage) 79 | }) 80 | 81 | It("supports allowing a method call on a double with variadic args", func() { 82 | AllowDouble(collaborator).To(ReceiveCallTo("VariadicQuery").With([]string{"arg1", "arg2", "arg3"}).AndReturn("result")) 83 | 84 | Expect(failHandlerCalled).To(BeFalse(), failHandlerMessage) 85 | 86 | result := subject.DelegateVariadicQuery("arg1", "arg2", "arg3") 87 | 88 | Expect(failHandlerCalled).To(BeFalse(), failHandlerMessage) 89 | Expect(result).To(Equal("result")) 90 | }) 91 | 92 | It("supports allowing a method call on a double with a custom behaviour", func() { 93 | AllowDouble(collaborator).To(ReceiveCallTo("Query").AndDo(func(arg string) string { 94 | if arg == "arg" { 95 | return "result" 96 | } 97 | 98 | return "" 99 | })) 100 | 101 | Expect(failHandlerCalled).To(BeFalse(), failHandlerMessage) 102 | 103 | result := subject.DelegateQuery("arg") 104 | 105 | Expect(failHandlerCalled).To(BeFalse(), failHandlerMessage) 106 | Expect(result).To(Equal("result")) 107 | }) 108 | }) 109 | 110 | type Collaborator interface { 111 | Query(string) string 112 | Command(string) (string, error) 113 | CommandWithNoReturnValues(string) 114 | VariadicQuery(...string) string 115 | } 116 | 117 | type CollaboratorDouble struct { 118 | Double 119 | } 120 | 121 | func NewCollaboratorDouble() CollaboratorDouble { 122 | return CollaboratorDouble{Double: NewStrictDoubleWithTypeOf(CollaboratorDouble{})} 123 | } 124 | 125 | func (d CollaboratorDouble) Query(arg string) string { 126 | returnValues, err := d.Call("Query", arg) 127 | if err != nil { 128 | return "" 129 | } 130 | 131 | return returnValues[0].(string) 132 | } 133 | 134 | func (d CollaboratorDouble) Command(arg string) (string, error) { 135 | returnValues, err := d.Call("Command", arg) 136 | if err != nil { 137 | return "", nil 138 | } 139 | 140 | returnedString, _ := returnValues[0].(string) 141 | returnedError, _ := returnValues[1].(error) 142 | 143 | return returnedString, returnedError 144 | } 145 | 146 | func (d CollaboratorDouble) CommandWithNoReturnValues(arg string) { 147 | d.Call("CommandWithNoReturnValues", arg) 148 | } 149 | 150 | func (d CollaboratorDouble) VariadicQuery(args ...string) string { 151 | returnValues, err := d.Call("VariadicQuery", args) 152 | if err != nil { 153 | return "" 154 | } 155 | 156 | return returnValues[0].(string) 157 | } 158 | 159 | type Subject struct { 160 | collaborator Collaborator 161 | } 162 | 163 | func NewSubject(collaborator Collaborator) Subject { 164 | return Subject{collaborator: collaborator} 165 | } 166 | 167 | func (s Subject) DelegateQuery(arg string) string { 168 | return s.collaborator.Query(arg) 169 | } 170 | 171 | func (s Subject) DelegateCommand(arg string) (string, error) { 172 | return s.collaborator.Command(arg) 173 | } 174 | 175 | func (s Subject) DelegateVariadicQuery(args ...string) string { 176 | return s.collaborator.VariadicQuery(args...) 177 | } 178 | 179 | func (s Subject) DelegateCommandWithNoReturnValues(arg string) { 180 | s.collaborator.CommandWithNoReturnValues(arg) 181 | } 182 | -------------------------------------------------------------------------------- /double_test.go: -------------------------------------------------------------------------------- 1 | package moka 2 | 3 | import ( 4 | "errors" 5 | 6 | . "github.com/onsi/ginkgo" 7 | . "github.com/onsi/gomega" 8 | ) 9 | 10 | var testFailHandlerInvoked bool 11 | var testFailMessage string 12 | 13 | func testFailHandler(message string, callerSkip ...int) { 14 | if !testFailHandlerInvoked { 15 | testFailHandlerInvoked = true 16 | testFailMessage = message 17 | } 18 | } 19 | 20 | func resetTestFail() { 21 | testFailHandlerInvoked = false 22 | testFailMessage = "" 23 | } 24 | 25 | var _ = Describe("StrictDouble", func() { 26 | var interactionValidator fakeInteractionValidator 27 | var double *StrictDouble 28 | 29 | BeforeEach(func() { 30 | interactionValidator = newFakeInteractionValidator(nil) 31 | resetTestFail() 32 | }) 33 | 34 | JustBeforeEach(func() { 35 | double = newStrictDoubleWithInteractionValidatorAndFailHandler(interactionValidator, testFailHandler) 36 | }) 37 | 38 | Describe("addInteraction", func() { 39 | JustBeforeEach(func() { 40 | double.addInteraction(newFakeInteraction([]interface{}{"result"}, true, nil, nil)) 41 | }) 42 | 43 | Context("when the interaction is valid", func() { 44 | BeforeEach(func() { 45 | interactionValidator = newFakeInteractionValidator(nil) 46 | }) 47 | 48 | It("succeeds", func() { 49 | By("not making the test fail", func() { 50 | Expect(testFailHandlerInvoked).To(BeFalse()) 51 | }) 52 | 53 | By("adding the interaction to the double", func() { 54 | result, err := double.Call("", []interface{}{}) 55 | 56 | Expect(result).To(Equal([]interface{}{"result"})) 57 | Expect(err).NotTo(HaveOccurred()) 58 | }) 59 | }) 60 | }) 61 | 62 | Context("when the interaction is not valid", func() { 63 | BeforeEach(func() { 64 | interactionValidator = newFakeInteractionValidator(errors.New("invalid interaction")) 65 | }) 66 | 67 | It("fails", func() { 68 | By("making the test fail", func() { 69 | Expect(testFailHandlerInvoked).To(BeTrue()) 70 | Expect(testFailMessage).To(Equal("invalid interaction")) 71 | }) 72 | 73 | By("not adding the interaction to the double", func() { 74 | result, err := double.Call("", []interface{}{}) 75 | 76 | Expect(result).To(BeNil()) 77 | Expect(err).To(HaveOccurred()) 78 | }) 79 | }) 80 | }) 81 | }) 82 | 83 | Describe("Call", func() { 84 | var firstInteraction *fakeInteraction 85 | var secondInteraction *fakeInteraction 86 | var thirdInteraction *fakeInteraction 87 | 88 | var returnValues []interface{} 89 | var err error 90 | 91 | JustBeforeEach(func() { 92 | double.addInteraction(firstInteraction) 93 | double.addInteraction(secondInteraction) 94 | double.addInteraction(thirdInteraction) 95 | 96 | returnValues, err = double.Call("UltimateQuestion", "life", "universe", "everything") 97 | }) 98 | 99 | Context("when some interactions match", func() { 100 | BeforeEach(func() { 101 | firstInteraction = newFakeInteraction(nil, false, nil, nil) 102 | secondInteraction = newFakeInteraction([]interface{}{42, nil}, true, nil, nil) 103 | thirdInteraction = newFakeInteraction([]interface{}{43, nil}, true, nil, nil) 104 | }) 105 | 106 | It("returns the configured return values", func() { 107 | By("stopping at the first matching interaction", func() { 108 | Expect(firstInteraction.callCalled).To(BeTrue()) 109 | Expect(secondInteraction.callCalled).To(BeTrue()) 110 | Expect(thirdInteraction.callCalled).To(BeFalse()) 111 | }) 112 | 113 | By("returning its return values", func() { 114 | Expect(returnValues).To(Equal([]interface{}{42, nil})) 115 | }) 116 | 117 | By("not returning an error", func() { 118 | Expect(err).NotTo(HaveOccurred()) 119 | }) 120 | 121 | By("not invoking the fail handler", func() { 122 | Expect(testFailHandlerInvoked).To(BeFalse()) 123 | }) 124 | }) 125 | }) 126 | 127 | Context("when no interaction matches", func() { 128 | BeforeEach(func() { 129 | firstInteraction = newFakeInteraction(nil, false, nil, nil) 130 | secondInteraction = newFakeInteraction(nil, false, nil, nil) 131 | thirdInteraction = newFakeInteraction(nil, false, nil, nil) 132 | }) 133 | 134 | It("makes the test fail", func() { 135 | By("calling all interactions", func() { 136 | Expect(firstInteraction.callCalled).To(BeTrue()) 137 | Expect(secondInteraction.callCalled).To(BeTrue()) 138 | Expect(thirdInteraction.callCalled).To(BeTrue()) 139 | }) 140 | 141 | By("returning nil", func() { 142 | Expect(returnValues).To(BeNil()) 143 | }) 144 | 145 | By("calling the fail handler", func() { 146 | Expect(testFailHandlerInvoked).To(BeTrue()) 147 | Expect(testFailMessage).To(Equal("Unexpected interaction: UltimateQuestion(\"life\", \"universe\", \"everything\")")) 148 | }) 149 | 150 | By("returning an error", func() { 151 | Expect(err).To(MatchError("Unexpected interaction: UltimateQuestion(\"life\", \"universe\", \"everything\")")) 152 | }) 153 | }) 154 | }) 155 | }) 156 | 157 | Describe("verifyInteractions", func() { 158 | var firstInteraction *fakeInteraction 159 | var secondInteraction *fakeInteraction 160 | var thirdInteraction *fakeInteraction 161 | 162 | JustBeforeEach(func() { 163 | double.addInteraction(firstInteraction) 164 | double.addInteraction(secondInteraction) 165 | double.addInteraction(thirdInteraction) 166 | 167 | double.verifyInteractions() 168 | }) 169 | 170 | Context("when all interactions are verified", func() { 171 | BeforeEach(func() { 172 | firstInteraction = newFakeInteraction(nil, false, nil, nil) 173 | secondInteraction = newFakeInteraction(nil, false, nil, nil) 174 | thirdInteraction = newFakeInteraction(nil, false, nil, nil) 175 | }) 176 | 177 | It("lets the test pass", func() { 178 | By("verifying all interactions", func() { 179 | Expect(firstInteraction.verifyCalled).To(BeTrue()) 180 | Expect(secondInteraction.verifyCalled).To(BeTrue()) 181 | Expect(thirdInteraction.verifyCalled).To(BeTrue()) 182 | }) 183 | 184 | By("not invoking the fail handler", func() { 185 | Expect(testFailHandlerInvoked).To(BeFalse()) 186 | }) 187 | }) 188 | }) 189 | 190 | Context("when some interactions are not verified", func() { 191 | BeforeEach(func() { 192 | firstInteraction = newFakeInteraction(nil, false, nil, nil) 193 | secondInteraction = newFakeInteraction(nil, false, errors.New("nope"), nil) 194 | thirdInteraction = newFakeInteraction(nil, false, nil, nil) 195 | }) 196 | 197 | It("makes the test fail", func() { 198 | By("stopping at the first unverified interaction", func() { 199 | Expect(firstInteraction.verifyCalled).To(BeTrue()) 200 | Expect(secondInteraction.verifyCalled).To(BeTrue()) 201 | Expect(thirdInteraction.verifyCalled).To(BeFalse()) 202 | }) 203 | 204 | By("invoking the fail handler", func() { 205 | Expect(testFailHandlerInvoked).To(BeTrue()) 206 | Expect(testFailMessage).To(Equal("nope")) 207 | }) 208 | }) 209 | }) 210 | }) 211 | }) 212 | -------------------------------------------------------------------------------- /interaction.go: -------------------------------------------------------------------------------- 1 | package moka 2 | 3 | import ( 4 | "fmt" 5 | "reflect" 6 | ) 7 | 8 | type interaction interface { 9 | call(methodName string, args []interface{}) ([]interface{}, bool) 10 | verify() error 11 | checkType(t reflect.Type) error 12 | } 13 | 14 | type argsInteraction struct { 15 | methodName string 16 | args []interface{} 17 | returnValues []interface{} 18 | } 19 | 20 | func newArgsInteraction(methodName string, args []interface{}, returnValues []interface{}) argsInteraction { 21 | return argsInteraction{methodName: methodName, args: args, returnValues: returnValues} 22 | } 23 | 24 | func (i argsInteraction) call(methodName string, args []interface{}) ([]interface{}, bool) { 25 | methodNamesAreEqual := i.methodName == methodName 26 | argsAreEqual := i.args == nil || reflect.DeepEqual(i.args, args) 27 | 28 | if methodNamesAreEqual && argsAreEqual { 29 | return i.returnValues, true 30 | } 31 | 32 | return nil, false 33 | } 34 | 35 | func (i argsInteraction) verify() error { 36 | return nil 37 | } 38 | 39 | func (i argsInteraction) String() string { 40 | return formatMethodCall(i.methodName, i.args) 41 | } 42 | 43 | func (i argsInteraction) checkType(t reflect.Type) error { 44 | method, methodExists := t.MethodByName(i.methodName) 45 | 46 | if !methodExists { 47 | return fmt.Errorf("Invalid interaction: type '%s' has no method '%s'", t.Name(), i.methodName) 48 | } 49 | 50 | if i.args != nil { 51 | expectedArgTypes := methodArgTypes(t, method) 52 | 53 | expectedNumberOfArgs := len(expectedArgTypes) 54 | numberOfArgs := len(i.args) 55 | if expectedNumberOfArgs != numberOfArgs { 56 | return fmt.Errorf( 57 | "Invalid interaction: method '%s.%s' takes %d arguments, %d specified", 58 | t.Name(), 59 | method.Name, 60 | expectedNumberOfArgs, 61 | numberOfArgs, 62 | ) 63 | } 64 | 65 | for i, arg := range i.args { 66 | argType := reflect.TypeOf(arg) 67 | expectedType := expectedArgTypes[i] 68 | if !assignable(argType, expectedType) { 69 | return fmt.Errorf( 70 | "Invalid interaction: type of argument %d of method '%s.%s' is '%s', '%s' given", 71 | i+1, 72 | t.Name(), 73 | method.Name, 74 | typeString(expectedType), 75 | typeString(argType), 76 | ) 77 | } 78 | } 79 | } 80 | 81 | expectedNumberOfReturnValues := method.Type.NumOut() 82 | numberOfReturnValues := len(i.returnValues) 83 | if numberOfReturnValues != expectedNumberOfReturnValues { 84 | return fmt.Errorf( 85 | "Invalid interaction: method '%s.%s' returns %d values, %d specified", 86 | t.Name(), 87 | method.Name, 88 | expectedNumberOfReturnValues, 89 | numberOfReturnValues, 90 | ) 91 | } 92 | 93 | for i, returnValue := range i.returnValues { 94 | returnValueType := reflect.TypeOf(returnValue) 95 | expectedType := method.Type.Out(i) 96 | if !assignable(returnValueType, expectedType) { 97 | return fmt.Errorf( 98 | "Invalid interaction: type of return value %d of method '%s.%s' is '%s', '%s' given", 99 | i+1, 100 | t.Name(), 101 | method.Name, 102 | typeString(expectedType), 103 | typeString(returnValueType), 104 | ) 105 | } 106 | } 107 | 108 | return nil 109 | } 110 | 111 | type bodyInteraction struct { 112 | methodName string 113 | body interface{} 114 | } 115 | 116 | func newBodyInteraction(methodName string, body interface{}) bodyInteraction { 117 | return bodyInteraction{methodName: methodName, body: body} 118 | } 119 | 120 | func (i bodyInteraction) call(methodName string, args []interface{}) ([]interface{}, bool) { 121 | if methodName == i.methodName { 122 | bodyAsValue := reflect.ValueOf(i.body) 123 | argsAsValues := interfacesToValues(args) 124 | returnValuesAsValues := bodyAsValue.Call(argsAsValues) 125 | returnValuesAsInterfaces := valuesToInterfaces(returnValuesAsValues) 126 | return returnValuesAsInterfaces, true 127 | } 128 | 129 | return nil, false 130 | } 131 | 132 | func interfacesToValues(interfaces []interface{}) []reflect.Value { 133 | values := []reflect.Value{} 134 | for _, i := range interfaces { 135 | values = append(values, reflect.ValueOf(i)) 136 | } 137 | return values 138 | } 139 | 140 | func valuesToInterfaces(values []reflect.Value) []interface{} { 141 | interfaces := []interface{}{} 142 | for _, v := range values { 143 | interfaces = append(interfaces, v.Interface()) 144 | } 145 | return interfaces 146 | } 147 | 148 | func (i bodyInteraction) verify() error { 149 | return nil 150 | } 151 | 152 | func (i bodyInteraction) checkType(t reflect.Type) error { 153 | method, methodExists := t.MethodByName(i.methodName) 154 | 155 | if !methodExists { 156 | return fmt.Errorf("Invalid interaction: type '%s' has no method '%s'", t.Name(), i.methodName) 157 | } 158 | 159 | bodyType := reflect.TypeOf(i.body) 160 | expectedArgTypes := methodArgTypes(t, method) 161 | 162 | expectedNumberOfArgs := len(expectedArgTypes) 163 | numberOfArgs := bodyType.NumIn() 164 | if expectedNumberOfArgs != numberOfArgs { 165 | return fmt.Errorf( 166 | "Invalid interaction: method '%s.%s' takes %d arguments, provided func takes %d", 167 | t.Name(), 168 | method.Name, 169 | expectedNumberOfArgs, 170 | numberOfArgs, 171 | ) 172 | } 173 | 174 | for i, expectedType := range expectedArgTypes { 175 | argType := bodyType.In(i) 176 | if argType != expectedType { 177 | return fmt.Errorf( 178 | "Invalid interaction: type of argument %d of method '%s.%s' is '%s', type of argument %d of provided func is '%s'", 179 | i+1, 180 | t.Name(), 181 | method.Name, 182 | typeString(expectedType), 183 | i+1, 184 | typeString(argType), 185 | ) 186 | } 187 | } 188 | 189 | expectedNumberOfReturnValues := method.Type.NumOut() 190 | numberOfReturnValues := bodyType.NumOut() 191 | if numberOfReturnValues != expectedNumberOfReturnValues { 192 | return fmt.Errorf( 193 | "Invalid interaction: method '%s.%s' returns %d values, provided func returns %d", 194 | t.Name(), 195 | method.Name, 196 | expectedNumberOfReturnValues, 197 | numberOfReturnValues, 198 | ) 199 | } 200 | 201 | for i := 0; i < method.Type.NumOut(); i++ { 202 | returnValueType := bodyType.Out(i) 203 | expectedType := method.Type.Out(i) 204 | if returnValueType != expectedType { 205 | return fmt.Errorf( 206 | "Invalid interaction: type of return value %d of method '%s.%s' is '%s', type of return value %d of provided func is '%s'", 207 | i+1, 208 | t.Name(), 209 | method.Name, 210 | typeString(expectedType), 211 | i+1, 212 | typeString(returnValueType), 213 | ) 214 | } 215 | } 216 | 217 | return nil 218 | } 219 | 220 | type expectedInteraction struct { 221 | interaction interaction 222 | called bool 223 | } 224 | 225 | func newExpectedInteraction(interaction interaction) *expectedInteraction { 226 | return &expectedInteraction{interaction: interaction} 227 | } 228 | 229 | func (i *expectedInteraction) call(methodName string, args []interface{}) ([]interface{}, bool) { 230 | returnValues, matches := i.interaction.call(methodName, args) 231 | i.called = matches 232 | return returnValues, matches 233 | } 234 | 235 | func (i *expectedInteraction) verify() error { 236 | if !i.called { 237 | return fmt.Errorf("Expected interaction: %s", i.interaction) 238 | } 239 | 240 | return nil 241 | } 242 | 243 | func (i *expectedInteraction) checkType(t reflect.Type) error { 244 | return nil 245 | } 246 | 247 | func assignable(leftType, rightType reflect.Type) bool { 248 | if leftType == nil { 249 | return isNillable(rightType) 250 | } 251 | 252 | return leftType.AssignableTo(rightType) 253 | } 254 | 255 | func isNillable(t reflect.Type) bool { 256 | return t.Kind() == reflect.Ptr || 257 | t.Kind() == reflect.Func || 258 | t.Kind() == reflect.Interface || 259 | t.Kind() == reflect.Slice || 260 | t.Kind() == reflect.Chan || 261 | t.Kind() == reflect.Map 262 | } 263 | 264 | func typeString(t reflect.Type) string { 265 | if t == nil { 266 | return "nil" 267 | } 268 | 269 | return t.String() 270 | } 271 | 272 | func methodArgTypes(t reflect.Type, method reflect.Method) []reflect.Type { 273 | argTypes := []reflect.Type{} 274 | fromIndex := 0 275 | if t.Kind() != reflect.Interface { 276 | fromIndex = 1 277 | } 278 | 279 | for i := fromIndex; i < method.Type.NumIn(); i++ { 280 | argTypes = append(argTypes, method.Type.In(i)) 281 | } 282 | 283 | return argTypes 284 | } 285 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | 3 |
4 | Moka 5 |

6 | 7 |

8 | A Go mocking framework. 9 |
10 | 11 | GoDOc 12 | 13 | 14 | TravisCI 15 | 16 | 17 | Go Report Card 18 | 19 |

20 | 21 | Moka is a mocking framework for the [Go programming 22 | language](https://golang.org). Moka works very well with the [Ginkgo testing 23 | framework](http://onsi.github.io/ginkgo), but can be easily used with any other 24 | testing framework, including the `testing` package from the standard library. 25 | 26 | ## Getting Moka 27 | 28 | ``` 29 | go get github.com/gcapizzi/moka 30 | ``` 31 | 32 | ## Setting Up Moka 33 | 34 | ### Ginkgo 35 | 36 | Moka is designed to play well with [Ginkgo](http://onsi.github.io/ginkgo). All 37 | you'll need to do is: 38 | 39 | * import the `moka` package; 40 | * register Ginkgo's `Fail` function as Moka's double fail handler using 41 | `RegisterDoublesFailHandler`. 42 | 43 | Here's an example: 44 | 45 | ```go 46 | package game_test 47 | 48 | import ( 49 | . "github.com/gcapizzi/moka" 50 | . "github.com/onsi/ginkgo" 51 | . "github.com/onsi/gomega" 52 | 53 | "testing" 54 | ) 55 | 56 | func TestGame(t *testing.T) { 57 | RegisterFailHandler(Fail) 58 | RegisterDoublesFailHandler(Fail) 59 | RunSpecs(t, "Game Suite") 60 | } 61 | ``` 62 | 63 | ### `testing` and other frameworks 64 | 65 | Support for the [`testing`](https://golang.org/pkg/testing) package hasn't been 66 | added yet, but this doesn't mean you can't use Moka with it. 67 | 68 | Here is the type for the Moka doubles fail handler: 69 | 70 | ```go 71 | type FailHandler func(message string, callerSkip ...int) 72 | ``` 73 | 74 | This type is modelled to match Ginkgo's `Fail` function. To use Moka with the 75 | `testing` package, just provide a doubles fail handler that makes the test 76 | fail! 77 | 78 | Here's an example: 79 | 80 | ```go 81 | package game 82 | 83 | import ( 84 | . "github.com/gcapizzi/moka" 85 | 86 | "testing" 87 | ) 88 | 89 | func TestGame(t *testing.T) { 90 | RegisterDoublesFailHandler(func(message string, callerSkip ...int) { 91 | t.Fatal(message) 92 | }) 93 | 94 | // use Moka here 95 | } 96 | ``` 97 | 98 | ## Getting Started: Building Your First Double 99 | 100 | A test double is an object that stands in for another object in your system 101 | during tests. The first step to use Moka is to declare a double type. The type 102 | will have to: 103 | 104 | * implement the same interface as the replaced object: this means that only 105 | objects used through interfaces can be replaced by Moka doubles; 106 | * embed the `moka.Double` type; 107 | * delegate any method that you'll need to stub/mock to the embedded 108 | `moka.Double` instance, using the `Call` method. 109 | 110 | Let's build a double type for a `Die` interface: 111 | 112 | ```go 113 | package dice 114 | 115 | import ( 116 | . "github.com/gcapizzi/moka" 117 | ) 118 | 119 | type Die interface { 120 | Roll(times int) []int 121 | } 122 | 123 | type DieDouble struct { 124 | Double 125 | } 126 | 127 | func NewDieDouble() DieDouble { 128 | return DieDouble{Double: NewStrictDouble()} 129 | } 130 | 131 | func (d DieDouble) Roll(times int) []int { 132 | returnValues, _ := d.Call("Roll", times) 133 | returnedRolls, _ := returnValues[0].([]int) 134 | return returnedRolls 135 | } 136 | ``` 137 | 138 | Some notes: 139 | 140 | * The `Double` instance we are embedding is of type `StrictDouble`: strict 141 | doubles will fail the test if they receive a call on a method that wasn't 142 | previously allowed or expected. 143 | * If the `Call` invocation fails, it will both return an error as its second 144 | return value, and invoke the fail handler. Since we know the fail handler 145 | will immediately stop the execution of the test, we don't need to check for 146 | the error. 147 | * This style of type assertions allow us to have `nil` return values. 148 | 149 | ## Allowing interactions 150 | 151 | Now that our double type is ready, let's use it in our tests! We will test a 152 | `Game` type, which looks like this: 153 | 154 | ```go 155 | package game 156 | 157 | type Game struct { 158 | die Die 159 | } 160 | 161 | func NewGame(die Die) Game { 162 | return Game{die: die} 163 | } 164 | 165 | func (g Game) Score() int { 166 | rolls := g.die.Roll(3) 167 | return rolls[0] + rolls[1] + rolls[2] 168 | } 169 | ``` 170 | 171 | Here is the test: 172 | 173 | ```go 174 | package game_test 175 | 176 | import ( 177 | . "github.com/gcapizzi/moka/examples/game" 178 | 179 | . "github.com/gcapizzi/moka" 180 | . "github.com/onsi/ginkgo" 181 | . "github.com/onsi/gomega" 182 | ) 183 | 184 | var _ = Describe("Game", func() { 185 | var die DieDouble 186 | var game Game 187 | 188 | BeforeEach(func() { 189 | die = NewDieDouble() 190 | game = NewGame(die) 191 | }) 192 | 193 | Describe("Score", func() { 194 | It("returns the sum of three die rolls", func() { 195 | AllowDouble(die).To(ReceiveCallTo("Roll").With(3).AndReturn([]int{1, 2, 3})) 196 | 197 | Expect(game.Score()).To(Equal(6)) 198 | }) 199 | }) 200 | }) 201 | ``` 202 | 203 | ## Typed doubles 204 | 205 | You might be wondering: what happens if I allow a method call that would be 206 | impossible to perform, given the type of my double? Let's say we forgot how the 207 | `Die` interface was defined, and wrote a test like this: 208 | 209 | ```go 210 | Describe("Score", func() { 211 | It("returns the sum of three die rolls", func() { 212 | AllowDouble(die).To(ReceiveCallTo("Cast").With(3).AndReturn([]int{1, 2, 3})) 213 | 214 | Expect(game.Score()).To(Equal(9)) 215 | }) 216 | }) 217 | ``` 218 | 219 | The `Die` interface has no method called `Cast`, so our configured interaction 220 | will never happen! 221 | 222 | To avoid this kind of problems, Moka provides _typed 223 | doubles_, which are associated with a type and will make sure that any 224 | configured interaction actually matches the type. 225 | 226 | To instantiate a typed double, use the `NewStrictDoubleWithTypeOf` constructor: 227 | 228 | ```go 229 | func NewDieDouble() DieDouble { 230 | return DieDouble{Double: NewStrictDoubleWithTypeOf(DieDouble{})} 231 | } 232 | ``` 233 | 234 | If run against a typed double, the previous test would fail with a message like this: 235 | 236 | ``` 237 | Invalid interaction: type 'DieDouble' has no method 'Cast' 238 | ``` 239 | 240 | ## Expecting interactions 241 | 242 | Sometimes allowing a method call is not enough. Some methods have side effects, 243 | and we need to make sure they have been invoked in order to be confident that 244 | our code is working. 245 | 246 | For example, let's assume we added a `Logger` collaborator to our `Game` type: 247 | 248 | ```go 249 | package game 250 | 251 | import "fmt" 252 | 253 | type Logger interface { 254 | Log(message string) 255 | } 256 | 257 | type StdoutLogger struct{} 258 | 259 | func (l StdoutLogger) Log(message string) { 260 | fmt.Println(message) 261 | } 262 | ``` 263 | 264 | We'll start, as usual, by building our double type: 265 | 266 | ```go 267 | type LoggerDouble struct { 268 | Double 269 | } 270 | 271 | func NewLoggerDouble() LoggerDouble { 272 | return LoggerDouble{Double: NewStrictDoubleWithTypeOf(LoggerDouble{})} 273 | } 274 | 275 | func (d LoggerDouble) Log(message string) { 276 | d.Call("Log", message) 277 | } 278 | ``` 279 | 280 | We can now add the `Logger` collaborator to `Game`, and test their interaction: 281 | 282 | ```go 283 | Describe("Score", func() { 284 | It("returns the sum of three die rolls", func() { 285 | AllowDouble(die).To(ReceiveCallTo("Roll").With(3).AndReturn([]int{1, 2, 3})) 286 | ExpectDouble(logger).To(ReceiveCallTo("Log").With("[1, 2, 3]")) 287 | 288 | Expect(game.Score()).To(Equal(6)) 289 | 290 | VerifyCalls(logger) 291 | }) 292 | }) 293 | ``` 294 | 295 | We use `ExpectDouble` to expect method calls on a double, and `VerifyCalls` 296 | to verify that the calls have actually been made. 297 | 298 | ## Custom interaction behaviour 299 | 300 | If you need to specify a custom behaviour for your double interactions, of need 301 | to perform assertions on the arguments, you can specify a body for the 302 | interaction using `AndDo`: 303 | 304 | ```go 305 | Describe("Score", func() { 306 | It("returns the sum of three die rolls", func() { 307 | AllowDouble(die).To(ReceiveCallTo("Roll").AndDo(func(times int) []int { 308 | Expect(times).To(BeNumerically(">", 0)) 309 | 310 | rolls := []int{} 311 | for i := 0; i < times; i++ { 312 | rolls = append(rolls, i+1) 313 | } 314 | return rolls 315 | })) 316 | 317 | Expect(game.Score()).To(Equal(6)) 318 | }) 319 | }) 320 | ``` 321 | 322 | ## How does Moka compare to the other Go mocking frameworks? 323 | 324 | There are a lot of mocking libraries for Go out there, so why build a new one? 325 | Compared to those libraries, Moka offers: 326 | 327 | * A very readable syntax, inspired by RSpec. 328 | * A model that naturally supports stubbing or mocking different method calls 329 | with different arguments and return values, without the need to enforce any 330 | order, which would add unnecessary coupling between your tests and your 331 | implementation. 332 | * A relatively straightforward way to declare double types, without the need for 333 | a generator. We still plan to introduce a generator to make things even 334 | easier. 335 | * Strict doubles that will make your test fail on any unexpected interaction, 336 | instead of loose doubles that will return zero values and lead to confusing 337 | failures. 338 | 339 | On the other hand, Moka currently lacks: 340 | 341 | * Compile-time type safety: in order to offer such a flexible and readable 342 | syntax, Moka cannot use the Go type system to detect invalid stub/mock 343 | declarations at compile-time. When using typed doubles, Moka will instead 344 | detect those errors at runtime and fail the test. 345 | * Support for argument matchers: will be implemented soon. 346 | * Support for enforced order of interactions: will be implemented soon. 347 | 348 | ## Gotchas 349 | 350 | ### Variadic Methods 351 | 352 | Moka treats variadic arguments are regular slice arguments. This means that: 353 | 354 | * You should not unpack (as in `SomeFunction(args...)`) the slice containing 355 | the variadic values when passing it to `Call`. 356 | * You should use slices in place of variadic arguments when allowing or 357 | expecting method calls. 358 | 359 | For example, given a `Calculator` interface: 360 | 361 | ```go 362 | type Calculator interface { 363 | Add(numbers ...int) int 364 | } 365 | ``` 366 | 367 | This is how you should delegate `Add` to `Call` in the double implementation: 368 | 369 | ```go 370 | func (d CalculatorDouble) Add(numbers ...int) int { 371 | returnValues, _ := d.Call("Add", numbers) 372 | 373 | // ... 374 | } 375 | ``` 376 | 377 | And this is how you should allow a call to `Add`: 378 | 379 | ```go 380 | AllowDouble(calculator).To(ReceiveCallTo("Add").With([]int{1, 2, 3}).AndReturn(6)) 381 | ``` 382 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /interaction_test.go: -------------------------------------------------------------------------------- 1 | package moka 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "reflect" 7 | 8 | . "github.com/onsi/ginkgo" 9 | . "github.com/onsi/gomega" 10 | ) 11 | 12 | var _ = Describe("interaction", func() { 13 | Describe("argsInteraction", func() { 14 | var interaction interaction 15 | 16 | Describe("call", func() { 17 | var matched bool 18 | var returnValues []interface{} 19 | 20 | BeforeEach(func() { 21 | interaction = newArgsInteraction( 22 | "UltimateQuestion", 23 | []interface{}{"life", "universe", "everything"}, 24 | []interface{}{42, nil}, 25 | ) 26 | }) 27 | 28 | Context("when both the method name and the args match", func() { 29 | JustBeforeEach(func() { 30 | returnValues, matched = interaction.call("UltimateQuestion", []interface{}{"life", "universe", "everything"}) 31 | }) 32 | 33 | It("matches and returns its return values", func() { 34 | Expect(returnValues).To(Equal([]interface{}{42, nil})) 35 | Expect(matched).To(BeTrue()) 36 | }) 37 | }) 38 | 39 | Context("when the method name doesn't match", func() { 40 | JustBeforeEach(func() { 41 | returnValues, matched = interaction.call("DomandaFondamentale", []interface{}{"life", "universe", "everything"}) 42 | }) 43 | 44 | It("doesn't match and returns nil", func() { 45 | Expect(returnValues).To(BeNil()) 46 | Expect(matched).To(BeFalse()) 47 | }) 48 | }) 49 | 50 | Context("when the arguments don't match", func() { 51 | JustBeforeEach(func() { 52 | returnValues, matched = interaction.call("UltimateQuestion", []interface{}{"vita", "universo", "tutto quanto"}) 53 | }) 54 | 55 | It("doesn't match and returns nil", func() { 56 | Expect(returnValues).To(BeNil()) 57 | Expect(matched).To(BeFalse()) 58 | }) 59 | }) 60 | 61 | Context("when both method name and the arguments don't match", func() { 62 | JustBeforeEach(func() { 63 | returnValues, matched = interaction.call("DomandaFondamentale", []interface{}{"vita", "universo", "tutto quanto"}) 64 | }) 65 | 66 | It("doesn't match and returns nil", func() { 67 | Expect(returnValues).To(BeNil()) 68 | Expect(matched).To(BeFalse()) 69 | }) 70 | }) 71 | }) 72 | 73 | Describe("verify", func() { 74 | BeforeEach(func() { 75 | interaction = newArgsInteraction("", nil, nil) 76 | }) 77 | 78 | It("does nothing and always returns nil", func() { 79 | Expect(interaction.verify()).To(BeNil()) 80 | }) 81 | }) 82 | 83 | Describe("checkType", func() { 84 | var TestCheckType = func(t reflect.Type) { 85 | var checkTypeError error 86 | 87 | JustBeforeEach(func() { 88 | checkTypeError = interaction.checkType(t) 89 | }) 90 | 91 | Context("when the method is defined and all types match", func() { 92 | BeforeEach(func() { 93 | interaction = newArgsInteraction( 94 | "UltimateQuestion", 95 | []interface{}{"life", "universe", "everything"}, 96 | []interface{}{42, nil}, 97 | ) 98 | }) 99 | 100 | It("succeeds", func() { 101 | Expect(checkTypeError).NotTo(HaveOccurred()) 102 | }) 103 | }) 104 | 105 | Context("when the method is not defined", func() { 106 | BeforeEach(func() { 107 | interaction = newArgsInteraction( 108 | "WorstQuestion", 109 | []interface{}{"life", "universe", "everything"}, 110 | []interface{}{42, nil}, 111 | ) 112 | }) 113 | 114 | It("fails", func() { 115 | Expect(checkTypeError).To(MatchError(fmt.Sprintf("Invalid interaction: type '%s' has no method 'WorstQuestion'", t.Name()))) 116 | }) 117 | }) 118 | 119 | Context("when the number of arguments doesn't match", func() { 120 | BeforeEach(func() { 121 | interaction = newArgsInteraction( 122 | "UltimateQuestion", 123 | []interface{}{"life", "universe"}, 124 | []interface{}{42, nil}, 125 | ) 126 | }) 127 | 128 | It("fails", func() { 129 | Expect(checkTypeError).To(MatchError(fmt.Sprintf("Invalid interaction: method '%s.UltimateQuestion' takes 3 arguments, 2 specified", t.Name()))) 130 | }) 131 | }) 132 | 133 | Context("when the type of some arguments doesn't match", func() { 134 | BeforeEach(func() { 135 | interaction = newArgsInteraction( 136 | "UltimateQuestion", 137 | []interface{}{"life", "universe", 0}, 138 | []interface{}{42, nil}, 139 | ) 140 | }) 141 | 142 | It("fails", func() { 143 | Expect(checkTypeError).To(MatchError(fmt.Sprintf("Invalid interaction: type of argument 3 of method '%s.UltimateQuestion' is 'string', 'int' given", t.Name()))) 144 | }) 145 | }) 146 | 147 | Context("when nil is specified for a non-nillable type argument", func() { 148 | BeforeEach(func() { 149 | interaction = newArgsInteraction( 150 | "UltimateQuestion", 151 | []interface{}{"life", "universe", nil}, 152 | []interface{}{42, nil}, 153 | ) 154 | }) 155 | 156 | It("fails", func() { 157 | Expect(checkTypeError).To(MatchError(fmt.Sprintf("Invalid interaction: type of argument 3 of method '%s.UltimateQuestion' is 'string', 'nil' given", t.Name()))) 158 | }) 159 | }) 160 | 161 | Context("when nil is specified for a nillable type argument", func() { 162 | BeforeEach(func() { 163 | interaction = newArgsInteraction( 164 | "UltimateQuestionWithSlice", 165 | []interface{}{nil}, 166 | []interface{}{42, nil}, 167 | ) 168 | }) 169 | 170 | It("succeeds", func() { 171 | Expect(checkTypeError).NotTo(HaveOccurred()) 172 | }) 173 | }) 174 | 175 | Context("when the number of return values doesn't match", func() { 176 | BeforeEach(func() { 177 | interaction = newArgsInteraction( 178 | "UltimateQuestion", 179 | []interface{}{"life", "universe", "everything"}, 180 | []interface{}{42}, 181 | ) 182 | }) 183 | 184 | It("fails", func() { 185 | Expect(checkTypeError).To(MatchError(fmt.Sprintf("Invalid interaction: method '%s.UltimateQuestion' returns 2 values, 1 specified", t.Name()))) 186 | }) 187 | }) 188 | 189 | Context("when the type of return values don't match", func() { 190 | BeforeEach(func() { 191 | interaction = newArgsInteraction( 192 | "UltimateQuestion", 193 | []interface{}{"life", "universe", "everything"}, 194 | []interface{}{"forty-two", nil}, 195 | ) 196 | }) 197 | 198 | It("fails", func() { 199 | Expect(checkTypeError).To(MatchError(fmt.Sprintf("Invalid interaction: type of return value 1 of method '%s.UltimateQuestion' is 'int', 'string' given", t.Name()))) 200 | }) 201 | }) 202 | 203 | Context("when nil is specified for a non-nillable type return value", func() { 204 | BeforeEach(func() { 205 | interaction = newArgsInteraction( 206 | "UltimateQuestion", 207 | []interface{}{"life", "universe", "everything"}, 208 | []interface{}{nil, nil}, 209 | ) 210 | }) 211 | 212 | It("fails", func() { 213 | Expect(checkTypeError).To(MatchError(fmt.Sprintf("Invalid interaction: type of return value 1 of method '%s.UltimateQuestion' is 'int', 'nil' given", t.Name()))) 214 | }) 215 | }) 216 | } 217 | 218 | TestCheckType(reflect.TypeOf((*deepThought)(nil)).Elem()) 219 | TestCheckType(reflect.TypeOf(myDeepThought{})) 220 | }) 221 | 222 | Context("when no arguments are specified", func() { 223 | var matched bool 224 | var returnValues []interface{} 225 | var checkTypeError error 226 | 227 | BeforeEach(func() { 228 | interaction = newArgsInteraction( 229 | "UltimateQuestion", 230 | nil, 231 | []interface{}{42, nil}, 232 | ) 233 | }) 234 | 235 | Describe("call", func() { 236 | Context("when the method name matches", func() { 237 | JustBeforeEach(func() { 238 | returnValues, matched = interaction.call("UltimateQuestion", []interface{}{"anything"}) 239 | }) 240 | 241 | It("matches and returns its return values", func() { 242 | Expect(returnValues).To(Equal([]interface{}{42, nil})) 243 | Expect(matched).To(BeTrue()) 244 | }) 245 | }) 246 | 247 | Context("when the method name doesn't match", func() { 248 | JustBeforeEach(func() { 249 | returnValues, matched = interaction.call("DomandaFondamentale", []interface{}{"anything"}) 250 | }) 251 | 252 | It("doesn't match and returns nil", func() { 253 | Expect(returnValues).To(BeNil()) 254 | Expect(matched).To(BeFalse()) 255 | }) 256 | }) 257 | }) 258 | 259 | Describe("checkType", func() { 260 | JustBeforeEach(func() { 261 | checkTypeError = interaction.checkType(reflect.TypeOf(myDeepThought{})) 262 | }) 263 | 264 | Context("when the method is defined", func() { 265 | It("succeeds", func() { 266 | Expect(checkTypeError).NotTo(HaveOccurred()) 267 | }) 268 | }) 269 | }) 270 | }) 271 | }) 272 | 273 | Describe("expectedInteraction", func() { 274 | var expectedMethodName = "UltimateQuestion" 275 | var expectedArgs = []interface{}{"life", "universe", "everything"} 276 | 277 | var returnValues []interface{} 278 | var matched bool 279 | 280 | var fakeInteraction *fakeInteraction 281 | var expectedInteraction interaction 282 | 283 | JustBeforeEach(func() { 284 | expectedInteraction = newExpectedInteraction(fakeInteraction) 285 | returnValues, matched = expectedInteraction.call(expectedMethodName, expectedArgs) 286 | }) 287 | 288 | Context("when called with the expected method name and args", func() { 289 | BeforeEach(func() { 290 | fakeInteraction = newFakeInteraction([]interface{}{42, nil}, true, nil, nil) 291 | }) 292 | 293 | It("delegates to the wrapped interaction and records the call for verification", func() { 294 | Expect(returnValues).To(Equal([]interface{}{42, nil})) 295 | Expect(matched).To(Equal(true)) 296 | Expect(expectedInteraction.verify()).To(BeNil()) 297 | }) 298 | }) 299 | 300 | Context("when called with unexpected method names or args", func() { 301 | BeforeEach(func() { 302 | fakeInteraction = newFakeInteraction(nil, false, nil, nil) 303 | }) 304 | 305 | It("delegates to the wrapped interaction but doesn't record the call for verification", func() { 306 | Expect(returnValues).To(BeNil()) 307 | Expect(matched).To(Equal(false)) 308 | Expect(expectedInteraction.verify()).To(MatchError("Expected interaction: ")) 309 | }) 310 | }) 311 | }) 312 | 313 | Describe("bodyInteraction", func() { 314 | var interaction interaction 315 | 316 | BeforeEach(func() { 317 | interaction = newBodyInteraction( 318 | "UltimateQuestion", 319 | func(topicOne, topicTwo, topicThree string) (int, error) { 320 | if topicOne == "life" && topicTwo == "universe" && topicThree == "everything" { 321 | return 42, nil 322 | } 323 | 324 | return 0, errors.New("NOPE") 325 | }, 326 | ) 327 | }) 328 | 329 | Describe("call", func() { 330 | var matched bool 331 | var returnValues []interface{} 332 | 333 | Context("when the method name matches", func() { 334 | JustBeforeEach(func() { 335 | returnValues, matched = interaction.call("UltimateQuestion", []interface{}{"life", "universe", "everything"}) 336 | }) 337 | 338 | It("matches and returns the return values from the body", func() { 339 | Expect(returnValues).To(Equal([]interface{}{42, nil})) 340 | Expect(matched).To(BeTrue()) 341 | }) 342 | }) 343 | 344 | Context("when the method name doesn't match", func() { 345 | JustBeforeEach(func() { 346 | returnValues, matched = interaction.call("DomandaFondamentale", []interface{}{"life", "universe", "everything"}) 347 | }) 348 | 349 | It("matches and returns the return values from the body", func() { 350 | Expect(returnValues).To(BeNil()) 351 | Expect(matched).To(BeFalse()) 352 | }) 353 | }) 354 | }) 355 | 356 | Describe("verify", func() { 357 | It("does nothing and returns nil", func() { 358 | Expect(interaction.verify()).To(BeNil()) 359 | }) 360 | }) 361 | 362 | Describe("checkType", func() { 363 | var TestCheckType = func(t reflect.Type) { 364 | var checkTypeError error 365 | 366 | JustBeforeEach(func() { 367 | checkTypeError = interaction.checkType(t) 368 | }) 369 | 370 | Context("when the method is defined and all types match", func() { 371 | BeforeEach(func() { 372 | interaction = newBodyInteraction( 373 | "UltimateQuestion", 374 | func(topicOne, topicTwo, topicThree string) (int, error) { return 0, nil }, 375 | ) 376 | }) 377 | 378 | It("succeeds", func() { 379 | Expect(checkTypeError).NotTo(HaveOccurred()) 380 | }) 381 | }) 382 | 383 | Context("when the method is not defined", func() { 384 | BeforeEach(func() { 385 | interaction = newBodyInteraction( 386 | "WorstQuestion", 387 | func(topicOne, topicTwo, topicThree string) (int, error) { return 0, nil }, 388 | ) 389 | }) 390 | 391 | It("fails", func() { 392 | Expect(checkTypeError).To(MatchError(fmt.Sprintf("Invalid interaction: type '%s' has no method 'WorstQuestion'", t.Name()))) 393 | }) 394 | }) 395 | 396 | Context("when the number of arguments doesn't match", func() { 397 | BeforeEach(func() { 398 | interaction = newBodyInteraction( 399 | "UltimateQuestion", 400 | func(topicOne, topicTwo string) (int, error) { return 0, nil }, 401 | ) 402 | }) 403 | 404 | It("fails", func() { 405 | Expect(checkTypeError).To(MatchError(fmt.Sprintf("Invalid interaction: method '%s.UltimateQuestion' takes 3 arguments, provided func takes 2", t.Name()))) 406 | }) 407 | }) 408 | 409 | Context("when the argument types don't match", func() { 410 | BeforeEach(func() { 411 | interaction = newBodyInteraction( 412 | "UltimateQuestion", 413 | func(topicOne, topicTwo string, x interface{}) (int, error) { return 0, nil }, 414 | ) 415 | }) 416 | 417 | It("fails", func() { 418 | Expect(checkTypeError).To(MatchError(fmt.Sprintf("Invalid interaction: type of argument 3 of method '%s.UltimateQuestion' is 'string', type of argument 3 of provided func is 'interface {}'", t.Name()))) 419 | }) 420 | }) 421 | 422 | Context("when the number of return values doesn't match", func() { 423 | BeforeEach(func() { 424 | interaction = newBodyInteraction( 425 | "UltimateQuestion", 426 | func(topicOne, topicTwo, topicThree string) int { return 0 }, 427 | ) 428 | }) 429 | 430 | It("fails", func() { 431 | Expect(checkTypeError).To(MatchError(fmt.Sprintf("Invalid interaction: method '%s.UltimateQuestion' returns 2 values, provided func returns 1", t.Name()))) 432 | }) 433 | }) 434 | 435 | Context("when the return value types don't match", func() { 436 | BeforeEach(func() { 437 | interaction = newBodyInteraction( 438 | "UltimateQuestion", 439 | func(topicOne, topicTwo, topicThree string) (string, error) { return "", nil }, 440 | ) 441 | }) 442 | 443 | It("fails", func() { 444 | Expect(checkTypeError).To(MatchError(fmt.Sprintf("Invalid interaction: type of return value 1 of method '%s.UltimateQuestion' is 'int', type of return value 1 of provided func is 'string'", t.Name()))) 445 | }) 446 | }) 447 | } 448 | 449 | TestCheckType(reflect.TypeOf((*deepThought)(nil)).Elem()) 450 | TestCheckType(reflect.TypeOf(myDeepThought{})) 451 | }) 452 | }) 453 | }) 454 | 455 | type deepThought interface { 456 | UltimateQuestion(topicOne, topicTwo, topicThree string) (int, error) 457 | UltimateQuestionWithSlice(things []string) (int, error) 458 | } 459 | 460 | type myDeepThought struct{} 461 | 462 | func (dt myDeepThought) UltimateQuestion(topicOne, topicTwo, topicThree string) (int, error) { 463 | return 42, nil 464 | } 465 | 466 | func (dt myDeepThought) UltimateQuestionWithSlice(things []string) (int, error) { 467 | return 42, nil 468 | } 469 | --------------------------------------------------------------------------------