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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
