1

I have a package which does some error checking for specific error types. One of the errors is from an external package, its fields are all unexported as well as the relevant creation func, so I cant instantiate it in my test, like below.

type Error struct {
    message string
    condition bool
}

func (e *Error) IsCondition() bool {
    return e.condition
}

func NewError(message string) *Error {
    return &Error{message: message}
}

func newErrorWithCondition(message string, condition bool) *Error {
    return &Error{message: message, condition: condition}
}

I want to implement a test in my package that checks if the error has the condition set or, as a different path is executed in each case but have no way of instantiating it? Is there a way I can test this?

Im testing something thats like,

func HandleErr(err error) error {
    var specificError Error

    switch {
    case errors.As(err, &specificError):
        return something
    default:
        return another thing
    }
}
Person1
  • 109
  • 2
  • 10
  • 1
    More information is needed to say if your task is even sensible. You are definitely not supposed to be able to access unexported parts of a package. If you were supposed to, they would make them public. – Hymns For Disco Dec 06 '22 at 01:32
  • testing an api handler that calls out to other services that may return the above with above condition set. The error is specific to the package that it is being used in, for some reason but I can create an error without the condition set as shown above. Would it be better to just wrap it in another custom error I define like `type ErrorWithCondition struct` or something? – Person1 Dec 06 '22 at 02:32
  • You can create your own error type with the same `IsCondition` method (possibly wrapping the other), and then any code that needs to be interoperable with both error types can work with `type ErrorWithCondition interface { error; IsCondition() bool }`. – Hymns For Disco Dec 06 '22 at 02:51

0 Answers0