I find that to be able to unit test things in golang, I need to restructure them in an uncomfortable way in order to be able to mock their dependencies.
For example, say I want to test this simple http handler: func handleLogIn(w http.ResponseWriter, r *http.Request) { svc := pkg.NewExternalService() value1 := parseValue1(r) svc.CallThis(value1) value2 := parseValue2(r) svc.CallThat(value2) } I want to mock pkg.NewExternalService, then use httptest to make sure given a http.Request, svc will be called with the correctly values. Right now, the solution I can come up with: 1. create a closure to create the service instead: var newExternalService = func () Service { return pkg.NewExternalService() } 2. override it in test: newExternalService = func () Service { return &MockService{} } Notice how I'm forced to use a closure instead of a function declaration. And then I have to turn Service into an interface so I can return a mock in test. But that's not the end of it. If I ever need to access a field of Service, I'm screwed, because interfaces can't contain fields. So I also have to restructure Service to expose fields as methods. I feel catering to the ability to be tested has too big an impact on my original code, and if I have no control over the design for the original Service, it seems it will be very difficult to test to say the least. I wonder if there is a better solution? Regards, Glen -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.