Skip to content

Commit

Permalink
Add test to verify whether an error from a function is handled properly
Browse files Browse the repository at this point in the history
  • Loading branch information
survivorbat committed Nov 28, 2024
1 parent 1592352 commit 242ebd5
Showing 1 changed file with 29 additions and 1 deletion.
30 changes: 29 additions & 1 deletion errors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ func TestErrorResponseFrom_ReturnsExpectedResponsesOnErrorTypes(t *testing.T) {
}

errA := &AError{message: "It was the man with one hand!"}
errB := &BError{message: "It was the man with one hand!"}
errB := &BError{message: "It was the woman with 3 hands!"}

RegisterErrorHandlerOn(registry, &AError{}, callbackA)
RegisterErrorHandlerOn(registry, &BError{}, callbackB)
Expand Down Expand Up @@ -190,6 +190,34 @@ func TestErrorResponseFrom_ReturnsExpectedResponsesOnErrorStrings(t *testing.T)
assert.Equal(t, ctx, calledWithCtxB)
}

func TestErrorResponseFrom_HandlesErrorsFromMethodsProperly(t *testing.T) {
t.Parallel()
// Arrange
registry := NewErrorRegistry()
expectedResponse := "user-friendly error"

var calledWithErr *AError
callback := func(_ context.Context, err *AError) (int, any) {
calledWithErr = err
return http.StatusPaymentRequired, expectedResponse
}

err := func() error {
return &AError{message: "It was the man with one hand!"}
}()

RegisterErrorHandlerOn(registry, &AError{}, callback)

// Act
code, response := NewErrorResponseFrom(context.Background(), registry, err)

// Assert
assert.Equal(t, http.StatusPaymentRequired, code)
assert.Equal(t, expectedResponse, response)

assert.Equal(t, &AError{message: "It was the man with one hand!"}, calledWithErr)
}

func TestErrorResponseFrom_HandlesWrappedErrorsProperly(t *testing.T) {
t.Parallel()
// Arrange
Expand Down

0 comments on commit 242ebd5

Please sign in to comment.