Using grpc-wiremock to mock responses in integrated tests of gRPC services

Overview

Utilizando grpc-wiremock para mockar respostas em testes integrados de serviços gRPC

Este repositório possui um exemplo prático de como configurar e realizar testes integrados com respostas mockadas utilizando o gRPC Wiremock

Consulte também o artigo Utilizando gRPC Wiremock para mockar respostas gRPC em testes integrados para detalhes adicionais.

Stack

Fluxo resumido

Schema

Configurando um mock

Considere que o shopping-cart-service seja um microsservice que se comunica com o serviço payment-service e você precisa fazer testes integrados para o fluxo de sucesso e de erro do shopping-cart-service. Neste caso, como os serviços se comunicam via gRPC, um serviço de mock REST comum não será suficiente e neste ponto que entra o gRPC Wiremock. Para configurar uma resposta mockada você deve seguir os seguintes passos:

  • 1º Crie um diretório, por exemplo, wiremock e dentro dele crie um sub-diretório proto e coloque uma cópia dos arquivos .proto que definem os serviços que deverão ser mockados;

  • 2º Ainda dentro do diretório wiremock crie um sub-diretório chamado stubs e dentro de stubs crie outro sub-diretório chamado mappings (atenção a este ponto, o sub-diretório mappings é importante para o gRPC Wiremock). Dentro de mappings adicione arquivos JSON com a definição da requisição que será enviada e a resposta que deverá ser dada para aquela requisição. Um modelo básico ficaria assim:

{
  "request": {
    "method": "POST",
    "url": "/PaymentService/pay",
    "bodyPatterns": [
      {
        "equalToJson": {
          "name": "any name",
          "cardNumber": "CARD-NUMBER-HERE",
          "value": 100.00
        }
      }
    ]
  },
  "response": {
    "status": 200,
    "jsonBody": {
      "status": "PAYMENT_ACCEPT"
    }
  }
}

O JSON acima significa que toda vez que uma requisição for feita no endereço onde o grp-wiremock está sendo executado com os dados contidos no bloco request o bloco response definido será retornado. Os campos name, cardNumber e value devem ter os mesmos nomes e tipos de dados definidos no parâmetro de entrada do serviço "/PaymentService/pay", o mesmo vale para os campos contidos na resposta.

Como executar este exemplo

  • Importe a pasta do projeto na sua IDE de preferência, no exemplo uso o Intellij Community;
  • Feita a importação, execute a task generateProto do Gradle;
  • No diretório raiz do repositório execute docker-compose -f ./docker-compose-grpc-wiremock.yaml up --build para que uma instância do gRPC Wiremock seja inicializada;
  • Acesse o pacote de testes br.com.tony.shoppingcartservice.integration e execute a classe CreateOrderTestIT
  • Aguarde execução e pronto!
You might also like...
Espresso - Use Espresso to write concise, beautiful, and reliable Android UI tests
Espresso - Use Espresso to write concise, beautiful, and reliable Android UI tests

Espresso Use Espresso to write concise, beautiful, and reliable Android UI tests

Write Tests as Examples on the Method-under-test

Write Tests as Examples on the Method-under-test

A collection of tests and easy to reuse pieces of code for bdk-jvm and bdk-android

Readme This repo is a collection of tests and easy to reuse pieces of code for bdk-jvm and bdk-android. Note that they don't aim to provide a full cov

Easy Response Mocking for Retrofit using annotations

Response Mocking for Retrofit using annotations. Assume Provides safe and easy way to mock API responses for retrofit-okhttp3.

A program to calculate the distance traveled during the run the calories burned and the average speed Display data in more than one way using a graph
A program to calculate the distance traveled during the run the calories burned and the average speed Display data in more than one way using a graph

Running App Features: A program to calculate the distance traveled during the run the calories burned and the average speed Display data in more than

Wiremock-testing - WireMock - A great library to mock APIs in your tests and supports Junit5
Wiremock-testing - WireMock - A great library to mock APIs in your tests and supports Junit5

WireMock Testing WireMock is a great library to mock APIs in your tests and supp

Raccoon is a lightweight response mocking framework that can be easily integrated into the Android UI tests.
Raccoon is a lightweight response mocking framework that can be easily integrated into the Android UI tests.

Raccoon Medium Articles Checkout these article to get more insights about this library: How to integrate this in your Android Test Why Raccoon? There

A JUnit5 Platform TestEngine integrated with the official FHIR Validator to run profile and Questionnaire validation as tests.
A JUnit5 Platform TestEngine integrated with the official FHIR Validator to run profile and Questionnaire validation as tests.

🔥 FHIR Validator JUnit Engine A JUnit5 TestEngine to integrate the FHIR Validator into the JUnit5 ecosystem. Supports writing expected validation out

Kotlin microservices with REST, and gRPC using BFF pattern. This repository contains backend services. Everything is dockerized and ready to
Kotlin microservices with REST, and gRPC using BFF pattern. This repository contains backend services. Everything is dockerized and ready to "Go" actually "Kotlin" :-)

Microservices Kotlin gRPC Deployed in EC2, Check it out! This repo contains microservices written in Kotlin with BFF pattern for performing CRUD opera

Microservice-grpc-multi-language-example - gRPC communication on multiple language demonstration (spring kotlin, go, .NET core 6) Cross-platform GUI gRPC debugging proxy like charles but design for gRPC
Cross-platform GUI gRPC debugging proxy like charles but design for gRPC

Mediator Cross-platform GUI gRPC debugging proxy like charles but design for gRPC. Build with Netty (proxy protocol), Compose Desktop (GUI), Sisyphus

Android library that allows you to run your acceptance tests written in Gherkin in your Android instrumentation tests.
Android library that allows you to run your acceptance tests written in Gherkin in your Android instrumentation tests.

Green Coffee Green Coffee is a library that allows you to run your acceptance tests written in Gherkin in your Android instrumentation tests using the

A mobile application developed for *Android* devices, aimed at 11th grade students in which they can take some basic training tests for presentation of external tests.

ApliKTest11 Application with Kit of questions and Knowledge Test for the preparation of the Saber Test. Description A mobile application developed for

A Movie listing app with unit tests and a couple of UI tests

MovieListings App This app is a Movie listing app with unit tests and a couple of UI tests. The app gets a list of movies from a public API, and the d

🛸Voyager is a pragmatic navigation library built for, and seamlessly integrated with, Jetpack Compose.
🛸Voyager is a pragmatic navigation library built for, and seamlessly integrated with, Jetpack Compose.

Voyager is a pragmatic navigation library built for, and seamlessly integrated with, Jetpack Compose.

Pluto is a on-device debugger for Android applications, which helps in inspection of HTTP requests/responses, capture Crashes and ANRs and manipulating application data on-the-go.
Pluto is a on-device debugger for Android applications, which helps in inspection of HTTP requests/responses, capture Crashes and ANRs and manipulating application data on-the-go.

Pluto Pluto is a on-device debugger for Android applications, which helps in inspection of HTTP requests/responses, capture Crashes and ANRs and manip

A pluggable sealed API result type for modeling Retrofit responses.

A pluggable sealed API result type for modeling Retrofit responses.

Android Jetpack MVVM Boilerplate. Integrated with Jetpack dependencies, Hilt, Room, Okhttp, Retrofit, etc.
Android Jetpack MVVM Boilerplate. Integrated with Jetpack dependencies, Hilt, Room, Okhttp, Retrofit, etc.

Android Jetpack MVVM Boilerplate Android Jetpack MVVM Boilerplate a Jetpack based, MVVM boilerplate template project for Modern Android. Features Here

Utility library dedicated for functional & non-functional codebases to simplify modelling of success and failure responses for the JVM languages 🔀

Expressible Utility library, part of the panda-lang SDK, dedicated for functional codebases that require enhanced response handling. Express yourself

Owner
Tony A. Luz
Great interest in back-end with Java, Kotlin and front-end with Vue. Amazon AWS cloud student.
Tony A. Luz
A JUnit5 Platform TestEngine integrated with the official FHIR Validator to run profile and Questionnaire validation as tests.

?? FHIR Validator JUnit Engine A JUnit5 TestEngine to integrate the FHIR Validator into the JUnit5 ecosystem. Supports writing expected validation out

NAV IT 2 Feb 2, 2022
Android library that allows you to run your acceptance tests written in Gherkin in your Android instrumentation tests.

Green Coffee Green Coffee is a library that allows you to run your acceptance tests written in Gherkin in your Android instrumentation tests using the

Mauricio Togneri 227 Nov 21, 2022
Lightweight service for creating standalone mock, written in pure Kotlin with Netty container.

MockService The lightweight service for creating a standalone mock, written in pure Kotlin with Netty container. The service allows getting config fil

null 2 Oct 28, 2021
FinnAds - A sample project to fetch advertisements from a mock api

FinnAds ?? FinnAds is a sample project to fetch advertisements from a mock api.

Fatih Giriş 2 Jan 27, 2022
Automated tests using Rest-assured with Kotlin lang

Testes de API em Kotlin Pré-requisitos Instalar o Kotlin Ambiente Para executar os testes localmente, estou utilizando o ServeRest Link do Repo: https

Rafael Berçam 15 Dec 23, 2022
3 types of Tests in Android (Unit - instrumentation - UI)

UnitTestingPractice 3 types of Tests in Android Unit instrumentation (Integration) UI Unit Testing benefits confirm code work like a charm simulate Ap

Ahmed Tawfiq 8 Mar 23, 2022
Easily scale your Android Instrumentation Tests across Firebase Test Lab with Flank.

Easily scale your Android Instrumentation Tests across Firebase Test Lab with Flank.

Nelson Osacky 220 Nov 29, 2022
Most popular Mocking framework for unit tests written in Java

Most popular mocking framework for Java Current version is 3.x Still on Mockito 1.x? See what's new in Mockito 2! Mockito 3 does not introduce any bre

mockito 13.6k Jan 4, 2023
A library that makes it easier to write high quality automated acceptance tests

Getting started with Serenity and Cucumber Serenity BDD is a library that makes it easier to write high quality automated acceptance tests, with power

ricardo larrahondo 1 Oct 20, 2021
A simple project to help developers in writing their unit tests in Android Platform.

AndroidUnitTesting A simple project to help developers in writing their unit tests in Android Platform. This is not a multi-module project, but has th

Bruno Gabriel dos Santos 4 Nov 10, 2021