Skip to content

Instantly share code, notes, and snippets.

@braddle
Created July 17, 2019 16:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save braddle/f8c623e072dfadd8b6f92a453a1bd9b5 to your computer and use it in GitHub Desktop.
Save braddle/f8c623e072dfadd8b6f92a453a1bd9b5 to your computer and use it in GitHub Desktop.
Very simple example of testing with GoMock and Concurrency
package math
type Table struct {
Base int
Result int
}
type Random interface {
GenerateInt() int
}
func MultiplyTablesRandom(in <-chan Table, gen Random) <-chan Table {
out := make(chan Table)
go func() {
for t := range in {
t.Result = t.Base * gen.GenerateInt()
out <- t
}
close(out)
}()
return out
}
func MultiplyTables(in <-chan Table, num int) <-chan Table {
out := make(chan Table)
go func() {
for t := range in {
t.Result = t.Base * num
out <- t
}
close(out)
}()
return out
}
package math_test
import (
"testing"
mock_math "github.com/braddle/concurrency/math/math_mock"
"github.com/golang/mock/gomock"
"github.com/braddle/concurrency/math"
)
func TestMultiplyChannel(t *testing.T) {
in := make(chan math.Table, 3)
in <- math.Table{Base: 5}
in <- math.Table{Base: 10}
in <- math.Table{Base: 20}
out := math.MultiplyTables(in, 3)
a := <-out
b := <-out
c := <-out
if a.Base != 5 || a.Result != 15 {
t.Logf("Base:\t%d", a.Base)
t.Logf("Result:\t%d", a.Result)
t.Error("Multiplication failed")
}
if b.Base != 10 || b.Result != 30 {
t.Logf("Base:\t%d", a.Base)
t.Logf("Result:\t%d", a.Result)
t.Error("Multiplication failed")
}
if c.Base != 20 || c.Result != 60 {
t.Logf("Base:\t%d", a.Base)
t.Logf("Result:\t%d", a.Result)
t.Error("Multiplication failed")
}
}
func TestMultiplyChannelRandomNumber(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
in := make(chan math.Table, 3)
in <- math.Table{Base: 5}
in <- math.Table{Base: 10}
in <- math.Table{Base: 20}
random := mock_math.NewMockRandom(ctrl)
random.EXPECT().GenerateInt().Return(3).Times(3)
out := math.MultiplyTablesRandom(in, random)
a := <-out
b := <-out
c := <-out
if a.Base != 5 || a.Result != 15 {
t.Logf("Base:\t%d", a.Base)
t.Logf("Result:\t%d", a.Result)
t.Error("Multiplication failed")
}
if b.Base != 10 || b.Result != 30 {
t.Logf("Base:\t%d", a.Base)
t.Logf("Result:\t%d", a.Result)
t.Error("Multiplication failed")
}
if c.Base != 20 || c.Result != 60 {
t.Logf("Base:\t%d", a.Base)
t.Logf("Result:\t%d", a.Result)
t.Error("Multiplication failed")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment