QA Interview Hub · Knowledge base · Quizzes · Українська

API › gRPC

Mocking and virtualising gRPC dependencies in tests

A gRPC dependency in a test is replaced at one of three levels: an in-process fake, a stub driven by .proto, or a client mock. Only a server-level replacement keeps real deadlines, statuses and metadata. To keep the stand-in from drifting away from the provider, use a shared .proto, buf breaking in CI and a contract check against the real service.

An order service calls a gRPC pricing service. In the consumer's tests the real pricing service is unavailable, yet you need to check what happens when it answers UNAVAILABLE, does not fit the deadline, or breaks a stream halfway. A stand-in is needed, but where you put it decides what the test can notice at all.

Mechanism: three levels of replacement.

  • A fake service in the same process. An implementation of the service (a generated base class) is started as a real gRPC server and the client reaches it through a channel. In grpc-java that is InProcessServerBuilder and InProcessChannelBuilder: the call goes through the gRPC layer (serialisation, statuses, deadlines, metadata) but without a network or a port. Fast and deterministic;
  • A separate stub server driven by the schema. WireMock with the gRPC extension reads descriptors generated by protoc from your .proto (they go into the grpc directory of the WireMock root), converts messages to JSON, so the usual JSON matchers work, and responses can be templated. It needs WireMock 3.2.0 or newer. It suits consumers in different languages and environments where the stub is started as a container;
  • A mock of the generated client. In the consumer's code the client interface itself is replaced with a mocking library. The fastest, but all of gRPC is bypassed: the test no longer sees statuses, deadlines or metadata.

Why it works this way. Replacing at the client level checks only the consumer's own logic. Replacing at the server level keeps the real client in the test, and with it the real deadlines, retries and interceptors. So for "the dependency is down" scenarios you pick the first two levels and keep the client mock for tests of pure business logic.

Example: an in-process fake.

@Rule public final GrpcCleanupRule grpcCleanup = new GrpcCleanupRule();

@Test
public void usesCachedPriceWhenPricingIsDown() throws Exception {
  String name = InProcessServerBuilder.generateName();
  grpcCleanup.register(InProcessServerBuilder.forName(name).directExecutor()
      .addService(new PricingGrpc.PricingImplBase() {
        @Override
        public void getPrice(PriceRequest req, StreamObserver<PriceReply> out) {
          out.onError(Status.UNAVAILABLE.withDescription("pricing is down").asRuntimeException());
        }
      }).build().start());
  ManagedChannel channel = grpcCleanup.register(
      InProcessChannelBuilder.forName(name).directExecutor().build());

  OrderService service = new OrderService(PricingGrpc.newBlockingStub(channel));
  assertThat(service.quote("sku-1").source()).isEqualTo("cached");
}

GrpcCleanupRule closes the channel and the server at the end of the test, and generateName() gives each test a unique server name. directExecutor() makes execution more deterministic.

What to check with a stand-in.

  • Error statuses. The fake returns UNAVAILABLE, NOT_FOUND, RESOURCE_EXHAUSTED, and the consumer reacts as designed: a retry, a fallback answer, a clear error for the user;
  • Deadline. The fake answers with a delay longer than the client's deadline: the consumer must get DEADLINE_EXCEEDED and not hang. A client mock will not show this;
  • Streams. A break after a few messages, an empty stream, a slow stream;
  • Metadata. An interceptor in the fake checks that the client sent a token and a correlation id;
  • Call count. A counter in the fake shows how many times the client repeated the call after an error.

Limits: a stand-in is only an assumption. A fake and a stub say what you put into them, so they drift from the real provider the same way mocks in unit tests do. Three safeguards keep them honest. First: one source of .proto for both sides, not a copy in the consumer's repository. Second: buf breaking in the provider's CI catches incompatible schema changes. Third: semantics (which statuses the service really returns, which fields it fills) is checked by a contract test or a small set of calls against the real service. For gRPC contracts Pact has a plugin framework that accepts new transports, gRPC among them: check the Pact plugin directory for whether a plugin exists for your language.

Common mistakes.

  • A client mock in every test: everything is green until a missing deadline brings production down;
  • A stand-in that returns only success: the consumer's error branches are never executed;
  • A private copy of the .proto that fell behind the provider: the stand-in answers with a schema that no longer exists;
  • The channel and the server are not closed: tests affect each other and threads leak.

Check yourself

A consumer test with a mock of the generated client is green, yet in production the call to the pricing service hangs with no answer. What do the tests lack?

Answer

A client mock bypasses the gRPC layer, so the deadline never fires in the test. You need a fake or a stub at the server level that answers later than the deadline, and a check that the consumer gets DEADLINE_EXCEEDED instead of waiting forever.

A stub returns a field that the provider's new version of the .proto no longer has, and the consumer tests are green. How do you catch this?

Answer

The stand-in knows nothing about the schema change. What helps is a shared .proto source, buf breaking in the provider's CI, and a contract or smoke test against the real service that compares the real response with what the stand-in assumes.

In an interview. Junior: a gRPC dependency in a test is replaced with a stand-in to check how the service behaves when it returns an error or answers slowly. Senior: I choose the level of replacement by what the test must see: for deadlines, statuses and metadata an in-process fake or a schema-driven stub, not a client mock; and so that the stand-in does not lie, I keep a shared .proto, buf breaking and a contract check against the provider.

More articles in this chapter