AspNetCore.Docs/aspnetcore/grpc/test-client.md

3.1 KiB

title author description monikerRange ms.author ms.custom ms.date uid
Mock gRPC client in tests jamesnk Learn how to mock gRPC client in .NET tests. >= aspnetcore-3.1 jamesnk mvc 05/02/2022 grpc/test-client

Mock gRPC client in tests

By: James Newton-King

Testing is an important aspect of building stable and maintainable software. Part of writing high-quality tests is removing external dependencies. This article discusses using mock gRPC clients in tests to remove gRPC calls to external servers.

Example testable client app

To demonstrate client app tests, review the following type in the sample app.

View or download sample code (how to download)

The Worker is a BackgroundService that makes calls to a gRPC server.

[!code-csharp]

The preceding type:

For more information on the C# assets automatically generated by Grpc.Tools, see gRPC services with C#: Generated C# assets.

Mock a gRPC client

gRPC clients are concrete client types that are generated from .proto files. The concrete gRPC client has methods that translate to the gRPC service in the .proto file. For example, a service called Greeter generates a GreeterClient type with methods to call the service.

A mocking framework can mock a gRPC client type. When a mocked client is passed to the type, the test uses the mocked method instead of sending a gRPC call to a server.

[!code-csharp]

The preceding unit test:

  • Mocks IGreetRepository and TesterClient using Moq.
  • Starts the worker.
  • Verifies SaveGreeting is called with the greeting message returned by the mocked TesterClient.

Additional resources