moq/README.md

57 lines
1.2 KiB
Markdown
Raw Normal View History

2016-08-29 12:00:17 +02:00
# moq
2016-08-29 14:25:35 +02:00
Interface mocking tool for go generate.
By [Mat Ryer](https://twitter.com/matryer) and [David Hernandez](https://github.com/dahernan), with ideas lovingly stolen from [Ernesto Jimenez](https://github.com/ernesto-jimenez).
2016-08-29 14:00:18 +02:00
## Usage
```
2016-08-29 14:25:35 +02:00
moq InterfaceName -out mocks_test.go
```
## Install
```
go install github.com/matryer/moq
2016-08-29 14:00:18 +02:00
```
2016-08-29 14:30:24 +02:00
## How to use it
Mocking interfaces is a nice way to write unit tests where you can easily control the behaviour of the mocked object.
2016-08-29 14:31:32 +02:00
Moq creates a struct that has a function field for each method, which you can declare in your test code.
This this example, Moq generated the `EmailSenderMock` type:
2016-08-29 14:30:24 +02:00
```go
func TestCompleteSignup(t *testing.T) {
called := false
var sentTo string
2016-08-29 14:31:32 +02:00
mockedEmailSender = &EmailSenderMock{
2016-08-29 14:30:24 +02:00
SendFunc: func(to, subject, body string) error {
called = true
sentTo = to
return nil
},
}
CompleteSignUp("me@email.com", mockedEmailSender)
if called == false {
t.Error("Sender.Send expected")
}
if sentTo != "me@email.com" {
t.Errorf("unexpected recipient: %s", sentTo)
}
}
2016-08-29 14:31:32 +02:00
func CompleteSignUp(to string, sender EmailSender) {
// TODO: this
}
2016-08-29 14:30:24 +02:00
```
The mocked structure implements the interface, where each method calls the associated function field.