Skip to content

Instantly share code, notes, and snippets.

@jostyee
Forked from joshrotenberg/consumer_test.go
Last active August 29, 2015 14:16
Show Gist options
  • Save jostyee/af3e069fc425376ecb07 to your computer and use it in GitHub Desktop.
Save jostyee/af3e069fc425376ecb07 to your computer and use it in GitHub Desktop.
package consumer
import (
"errors"
"testing"
"github.com/bitly/go-nsq"
)
// tests nsq.HandlerFunc. just write the function in line in the test
// itself
func TestHandlerFunc(t *testing.T) {
testPayload := "this is a test"
msg := generateMessage(testPayload)
f := nsq.HandlerFunc(func(message *nsq.Message) error {
if string(message.Body) != testPayload {
return errors.New("payload didn't match")
}
return nil
})
err := f(msg)
if err != nil {
t.Fatal("handlerfunc didn't work!", err)
}
}
// or if you have a special handler type, do it this way. for this
// purpose, just a simple struct with a testing object for context.
type MyHandler struct {
expectedMessage string
t *testing.T
}
// and the HandleMessage func will use that object to log something
func (h *MyHandler) HandleMessage(message *nsq.Message) error {
if string(message.Body) != h.expectedMessage {
return errors.New("payload didn't match")
}
h.t.Log("i'm in MyHandler.HandleMessage!")
return nil
}
// tests MyHandler
func TestMyHandler(t *testing.T) {
testPayload := "this is another test"
msg := generateMessage(testPayload)
mh := &MyHandler{expectedMessage: testPayload, t: t}
err := mh.HandleMessage(msg)
if err != nil {
t.Fatal("handler didn't work!", err)
}
}
func generateMessage(payload string) *nsq.Message {
id := "1234567890asdfgh"
var i [nsq.MsgIDLength]byte
copy(i[:], id)
return nsq.NewMessage(i, []byte(payload))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment