Skip to content

Commit

Permalink
Merge pull request #42 from emilien-puget/panic_invalid_return_values
Browse files Browse the repository at this point in the history
Fix a panic using a When.ThenReturn
  • Loading branch information
ovechkin-dm authored Feb 12, 2024
2 parents e8cca63 + f5676f7 commit 2948932
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 2 deletions.
10 changes: 8 additions & 2 deletions registry/reporter.go
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,13 @@ func (e *EnrichedReporter) ReportInvalidReturnValues(instanceType reflect.Type,
outTypesSB.WriteString("(")
}
for i := 0; i < len(ret); i++ {
outTypesSB.WriteString(reflect.ValueOf(ret[i]).Type().String())
of := reflect.ValueOf(ret[i])
if of.Kind() == reflect.Invalid {
outTypesSB.WriteString("nil")
} else {
outTypesSB.WriteString(of.Type().String())
}

if i != len(ret)-1 {
outTypesSB.WriteString(", ")
}
Expand Down Expand Up @@ -298,4 +304,4 @@ func (e *EnrichedReporter) ReportUnexpectedMatcherDeclaration(m []*matcherWrappe
e.StackTraceErrorf(`Unexpected matchers declaration.
%s
Matchers can only be used inside When() method call.`, sb.String())
}
}
1 change: 1 addition & 0 deletions tests/when/when_double_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (

type WhenDoubleInterface interface {
Foo(a int) (int, error)
FooNullable(a int) (*int, error)
}

func TestWhenDoubleRet(t *testing.T) {
Expand Down
11 changes: 11 additions & 0 deletions tests/when/when_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
type WhenInterface interface {
Foo(a int) (int, string)
Bar(a int, b string, c string) (int, string)
NullableBar(a int, b string, c string) (*int, *string)
Empty() int
RespondWithMock() Nested
RespondWithSlice() []int
Expand Down Expand Up @@ -75,6 +76,16 @@ func TestNoMatchersAreExactOnReturn(t *testing.T) {
r.AssertEqual("2", s)
}

func TestIncorrectNumberReturnNullable(t *testing.T) {
r := common.NewMockReporter(t)
SetUp(r)
m := Mock[WhenInterface]()
When(m.NullableBar(10, "test1", "test2")).ThenReturn(nil)
_, _ = m.NullableBar(10, "test1", "test2")
r.AssertError()
r.ErrorContains("invalid return values")
}

func TestNoMatchersAreExactOnAnswer(t *testing.T) {
r := common.NewMockReporter(t)
SetUp(r)
Expand Down

0 comments on commit 2948932

Please sign in to comment.