Golang / GoLang System Architecture and Testing Interview Questions
What is contract testing and how does it apply to Go microservices?
Contract testing verifies that services honour their agreed API contracts without requiring a full integration test environment. In a microservices system, consumer-driven contract testing (Pact) lets service consumers define the API shape they expect, and providers verify they match.
// Pact consumer test (user-service-client) // Defines what the consumer expects from the user service func TestUserServiceContract_GetUser(t *testing.T) { // Define the expected interaction pact := dsl.Pact{ Consumer: "order-service", Provider: "user-service", } defer pact.Teardown() pact. AddInteraction(). Given("user 1 exists"). UponReceiving("a request for user 1"). WithRequest(dsl.Request{ Method: "GET", Path: "/users/1", Headers: dsl.MapMatcher{"Accept": "application/json"}, }). WillRespondWith(dsl.Response{ Status: 200, Body: dsl.Match(User{}), // matches structure, not values }) if err := pact.Verify(func() error { client := NewUserClient(pact.Server.URL) user, err := client.GetUser(context.Background(), 1) if err != nil { return err } if user.ID != 1 { return fmt.Errorf("expected ID 1, got %d", user.ID) } return nil }); err != nil { t.Fatal(err) } } // Protobuf contracts are already self-documenting // For gRPC: test that the proto file matches what clients use // Use protoc-gen-validate for field-level validation in the schema message CreateUserRequest { string email = 1 [(validate.rules).string.email = true]; string name = 2 [(validate.rules).string = {min_len: 1, max_len: 100}]; }
gRPC contract testing: Protobuf provides the contract itself. The pattern is different — ensure the generated Go code from the consumer's proto copy matches the provider's. Tools like buf breaking detect breaking changes in .proto files, acting as automated contract enforcement.
More Related questions...