Skip to content
This repository was archived by the owner on Jun 27, 2023. It is now read-only.

Commit b4b7d21

Browse files
authoredDec 23, 2019
add Len matcher (#368)
This matcher will check the length with any type that allows this behavior via reflection. Implementation inspired by #189.
1 parent 9be4808 commit b4b7d21

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed
 

‎gomock/matchers.go

+24
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,24 @@ func (am allMatcher) String() string {
176176
return strings.Join(ss, "; ")
177177
}
178178

179+
type lenMatcher struct {
180+
i int
181+
}
182+
183+
func (m lenMatcher) Matches(x interface{}) bool {
184+
v := reflect.ValueOf(x)
185+
switch v.Kind() {
186+
case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice, reflect.String:
187+
return v.Len() == m.i
188+
default:
189+
return false
190+
}
191+
}
192+
193+
func (m lenMatcher) String() string {
194+
return fmt.Sprintf("has length %d", m.i)
195+
}
196+
179197
// Constructors
180198

181199
// All returns a composite Matcher that returns true if and only all of the
@@ -192,6 +210,12 @@ func Any() Matcher { return anyMatcher{} }
192210
// Eq(5).Matches(4) // returns false
193211
func Eq(x interface{}) Matcher { return eqMatcher{x} }
194212

213+
// Len returns a matcher that matches on length. This matcher returns false if
214+
// is compared to a type that is not an array, chan, map, slice, or string.
215+
func Len(i int) Matcher {
216+
return lenMatcher{i}
217+
}
218+
195219
// Nil returns a matcher that matches if the received value is nil.
196220
//
197221
// Example usage:

‎gomock/matchers_test.go

+4
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,10 @@ func TestMatchers(t *testing.T) {
3838
[]e{"", 0, make(chan bool), errors.New("err"), new(int)}},
3939
{"test Not", gomock.Not(gomock.Eq(4)), []e{3, "blah", nil, int64(4)}, []e{4}},
4040
{"test All", gomock.All(gomock.Any(), gomock.Eq(4)), []e{4}, []e{3, "blah", nil, int64(4)}},
41+
{"test Len", gomock.Len(2),
42+
[]e{[]int{1, 2}, "ab", map[string]int{"a": 0, "b": 1}, [2]string{"a", "b"}},
43+
[]e{[]int{1}, "a", 42, 42.0, false, [1]string{"a"}},
44+
},
4145
}
4246
for _, tt := range tests {
4347
t.Run(tt.name, func(t *testing.T) {

0 commit comments

Comments
 (0)
This repository has been archived.