Gomega Matcher : A guide to developing your custom tests in Golang

About Gomega Matchers

type GomegaMatcher interface {
Match(actual interface{}) (success bool, err error)
FailureMessage(actual interface{}) (message string)
NegatedFailureMessage(actual interface{}) (message string)
}

Code Example

Comparison

// Person Struct to Compare
type Person struct {
Age []int
}
y (expected) = 2*x (age) + 10
// Match expects the actual item which is compared to the
// target returned from the custom Gomega function
func (p *Person) Match(actual interface{}) (bool, error) {
switch actual := actual.(type) {
case Person:
for i, j := range actual.Age {
if j != (2*p.Age[i] + 10) {
return false, fmt.Errorf("Wrong Person")
}
}
}
return true, nil
}
// FailureMessage method for Person struct
func (p *Person) FailureMessage(actual interface{}) string {
return fmt.Sprintf("Expected age to be %v but received %v", actual, p.Age)
}
// NegatedFailureMessage method for Person struct
func (p *Person) NegatedFailureMessage(actual interface{}) string {
return fmt.Sprintf("Expected age to be %v but received %v", actual, p.Age)
}

Defining our structs

package testimport (
"testing"
"goTest/human". "github.com/onsi/gomega"
"github.com/onsi/gomega/types"
)
func TestHumanStruct(t *testing.T) {
tests := []struct {
name string
targetAge []int
humanTarget human.Person
want bool
}{
{
name: "Compare Age Correct",
targetAge: []int{10, 20},
humanTarget: human.Person{Age: []int{30, 50}},
want: true,
},
{
name: "Compare Age Incorrect",
targetAge: []int{11, 25},
humanTarget: human.Person{Age: []int{32, 60}},
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
g := NewWithT(t)
g.Expect(tt.humanTarget).Should(MatchAge(tt.targetAge))
})
}
}
  • name -> define name of test
  • targetAge -> the age we want to test
  • humanTarget -> Actual values present here
  • want -> boolean result expected
// MatchAge is the Custom Gomega Testing Function
func MatchAge(a []int) types.GomegaMatcher {
return &human.Person{Age: a}
}

Running the Tests

go test -v

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store