Concurrent mocks for gRPC Elixir.
Add mock_grpc to your list of dependencies:
defdepsdo[{:mock_grpc,"~> 1.0"},# You also need to have gRPC Elixir installed{:grpc,"~> 0.6"}]endImagine that you have a module calling a say_hello RPC.
defmoduleDemododefsay_hello(name)do{:ok,channel}=GRPC.Stub.connect("localhost:50051")GreetService.Stub.say_hello(channel,%SayHelloRequest{name: "John Doe"})endendThe first step is to change the connect code to use an adapter coming from the app environment, so that you can use MockGRPC in test mode, and the default adapter in dev and production.
{:ok,channel}=GRPC.Stub.connect("localhost:50051",adapter: Application.get_env(:demo,:grpc_adapter))Or if you're using ConnGRPC, add adapter to the channel opts.
Then, on your config/test.exs, set it to MockGRPC.Adapter:
Application.put_env(:demo,:grpc_adapter,MockGRPC.Adapter)Now it's time to write your test. To enable mocks, add use MockGRPC to your test, and call MockGRPC.expect/2 or MockGRPC.expect/3 to set expectations.
defmoduleDemoTestdouseExUnit.Case,async: trueuseMockGRPCtest"say_hello/1"doMockGRPC.expect(&GreetService.Stub.say_hello/2,fnreq->assert%SayHelloRequest{name: "John Doe"}==req{:ok,%SayHelloResponse{message: "Hello John Doe"}}end)assert{:ok,%SayHelloResponse{message: "Hello John Doe"}}=Demo.say_hello("John Doe")endendFor more info, see MockGRPC on Hexdocs.
This project uses Contributor Covenant version 2.1. Check CODE_OF_CONDUCT.md file for more information.
MockGRPC source code is released under Apache License 2.0.