Skip to content

Managing Stubs Through the Generated Client

Rodrigo edited this page Mar 6, 2021 · 6 revisions

v1.4.0 added a generated client to allow the creation of stubs. It is a client to the REST API, so the stubs management is still effectively done through the REST API but using a much more intuitive interface.

Please refer to the Getting Started page for information on how to use the tool. In this wiki, we will focus on how to use generated client instead of the REST API directly to manage the stubs.

We will revisit our Greeter service definition.

syntax = "proto3";

package carvalhorr.greeter;

option go_package = ".;greeter_service";

service Greeter {
	rpc SayHello (HelloRequest) returns (HelloReply) {}
}

message HelloRequest {
	string name = 1;
}

message HelloReply {
	string message = 1;
}

After generating the mock you can use the generated client to create stubs like this:

import greetservice ... // the generated mock service

func TestSomething {

	...
	
	// Start the client pointing to the REST API
	m := greetservice.NewGreeterRemoteMockClient("127.0.0.1", 1068)

	// Metadata can be used for deciding which response to return
	md := metadata.Pairs("key1", "value1", "key2", "value2")
	ctx := metadata.NewOutgoingContext(context.Background(), md)

	// Mock a successfull response
	m.OnSayHello(ctx, &greetservice.HelloRequest{Name: "Rodrigo"}).
		Return(&greetservice.HelloReply{Message: "Hello, Rodrigo."})

	...

	// Delete existing mocks
	m.Clear()

	// Mock an error response
	m.OnSayHello(ctx, &greetservice.HelloRequest{Name: "Carvalho"}).
		Error(codes.NotFound, "Not found")

	...

	m.Clear()
}

The generated client now contains a constructor for the client New...RemoteMockClient that takes the IP and port to the mock server's REST API.

The generated ...RemoteMockClient exposes a method for each RPC defined in the corresponding Protobuf definition in the form OnMethod1, OnMethod2, etc. Each of them takes a context.Context and an instance of the corresponding request type. You can then determine if the stub mathing the request and context will return an error or a successful response by calling .Return(...) or .Error(...). .Return(...) takes the associated method's return type. .Error(...) takes an error code and message as defined in status.Status proto definition.

Limitations

  • At this moment it is possible to create stubs with exact matching through the generated client (See stub.request.match)
  • Error stubs are also limited to returning code and message. details is only supported through the use of the REST API (Advanced Error Mocking)
Clone this wiki locally