0

Currently I have some code which is structured like this:

type Service struct {
    // some dependencies
}

func (s *Service) FindStuff(ctx Context) { // this signature cannot be changed
    // some logic...
    isNew, err := s.isNewUser(ctx)

    if err != nil {
        // do stuff
    }

    if isNew {
        // call new flow
    } else {
        // call old flow
    }
}

func (s *Service) isNewUser(ctx Context) (bool, error) {
    value := apiGet("some-endpoint")
    // some logic...
    for {
        for {
            if  { return true, nil }
            if  { return false, nil }
            if  { return false, nil }
        }
    }
    return true, nil
}
  • The existing unit tests call FindStuff which calls isNewUser, the call apiGet("some-endpoint") is mocked.
  • The isNewUser method is used by multiple methods on the Service class.

In a Java world you could create a new class which has a method isNewUser you could then pass a mock object of that class as a dependency to Service and mock the call to isNewUser to throw an exception or return true or false and allow everything to be tested in isolation.

What is the most idiomatic Go way of testing this?

1
  • If you already have a mock for apiGet (which should probably be a method of some apiClient interface?) then can't you just make it return the data which would make isNewUser return with the needed result? – Ainar-G Mar 30 at 16:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.