mirror of https://github.com/stretchr/testify.git
IsType: A type-safe way of checking argument type
Like `assert.IsType(...)`, `mock.IsType` is used to check that the type of an argument is the expected type. This is an alternative to `AnythingOfType`.pull/881/head
parent
ea72eb9159
commit
518a1491c7
23
mock/mock.go
23
mock/mock.go
|
@ -578,6 +578,23 @@ func AnythingOfType(t string) AnythingOfTypeArgument {
|
|||
return AnythingOfTypeArgument(t)
|
||||
}
|
||||
|
||||
// IsTypeArgument is a struct that contains the type of an argument
|
||||
// for use when type checking. This is an alternative to AnythingOfType.
|
||||
// Used in Diff and Assert.
|
||||
type IsTypeArgument struct {
|
||||
t interface{}
|
||||
}
|
||||
|
||||
// IsType returns an IsTypeArgument object containing the type to check for.
|
||||
// You can provide a zero-value of the type to check. This is an
|
||||
// alternative to AnythingOfType. Used in Diff and Assert.
|
||||
//
|
||||
// For example:
|
||||
// Assert(t, IsType(""), IsType(0))
|
||||
func IsType(t interface{}) *IsTypeArgument {
|
||||
return &IsTypeArgument{t: t}
|
||||
}
|
||||
|
||||
// argumentMatcher performs custom argument matching, returning whether or
|
||||
// not the argument is matched by the expectation fixture function.
|
||||
type argumentMatcher struct {
|
||||
|
@ -711,6 +728,12 @@ func (args Arguments) Diff(objects []interface{}) (string, int) {
|
|||
output = fmt.Sprintf("%s\t%d: FAIL: type %s != type %s - %s\n", output, i, expected, reflect.TypeOf(actual).Name(), actualFmt)
|
||||
}
|
||||
|
||||
} else if reflect.TypeOf(expected) == reflect.TypeOf((*IsTypeArgument)(nil)) {
|
||||
t := expected.(*IsTypeArgument).t
|
||||
if reflect.TypeOf(t) != reflect.TypeOf(actual) {
|
||||
differences++
|
||||
output = fmt.Sprintf("%s\t%d: FAIL: type %s != type %s - %s\n", output, i, reflect.TypeOf(t).Name(), reflect.TypeOf(actual).Name(), actualFmt)
|
||||
}
|
||||
} else {
|
||||
|
||||
// normal checking
|
||||
|
|
|
@ -1257,6 +1257,24 @@ func Test_Arguments_Diff_WithAnythingOfTypeArgument_Failing(t *testing.T) {
|
|||
|
||||
}
|
||||
|
||||
func Test_Arguments_Diff_WithIsTypeArgument(t *testing.T) {
|
||||
var args = Arguments([]interface{}{"string", IsType(0), true})
|
||||
var count int
|
||||
_, count = args.Diff([]interface{}{"string", 123, true})
|
||||
|
||||
assert.Equal(t, 0, count)
|
||||
}
|
||||
|
||||
func Test_Arguments_Diff_WithIsTypeArgument_Failing(t *testing.T) {
|
||||
var args = Arguments([]interface{}{"string", IsType(""), true})
|
||||
var count int
|
||||
var diff string
|
||||
diff, count = args.Diff([]interface{}{"string", 123, true})
|
||||
|
||||
assert.Equal(t, 1, count)
|
||||
assert.Contains(t, diff, `string != type int - (int=123)`)
|
||||
}
|
||||
|
||||
func Test_Arguments_Diff_WithArgMatcher(t *testing.T) {
|
||||
matchFn := func(a int) bool {
|
||||
return a == 123
|
||||
|
|
Loading…
Reference in New Issue