Easy Response Mocking for Retrofit using annotations

Overview

Assume

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

Download

Add Jitpack repository in project build.gradle file


allprojects {
    repositories {
        ...
        maven { url "https://jitpack.io" }
    }
}

Add dependencies to your module's build.gradle file:


def assume_version = "1.1"

// kaptDebug to reduce unnecessary Annotation processing for release build generations
kaptDebug "com.github.aniketbhoite.Assume:processor:$assume_version"

// debugImplementation ensures APIs are mocked only in debug making it production safe
debugImplementation "com.github.aniketbhoite.Assume:annotations:$assume_version"

releaseImplementation "com.github.aniketbhoite.Assume:annotations-empty:$assume_version"

annotations-empty package adds empty placeholder classes. If you add annotation-empty then assume won't interfere with the actual response even if you keep the assume code in your codebase by mistake.

Usage

Add @Assume annotation to API method with wanted response, responseCode is optional


@Assume(
	responseCode = 200,
	response ="{\"page\":1,\"results\":[],\"total_pages\":10,\"total_results\":100}"
)
@POST("v2/top-headlines")
suspend fun getHeadline(): NewsResponse


@Assume(
	responseCode = 200,
        response = "{\"userId\": 1, \"id\": 1, \"title\": \"Test title 1\", \"body\": \"Test title 2\"}",
	ignore = true  //To get the actual response from network & skip Assume
)
@GET("posts/{id}")
suspend fun getPostById(@Path("id") id: Int): PostListModelItem

Add AssumeInterceptor inside the Okhttp3 client


val client = OkHttpClient.Builder()
        .addInterceptor(AssumeInterceptor(BASE_URL) //same base url added in retrofit
        .build()

You should be good to go.👍🏽

Benefits of Assume

  1. Saves hassles of modifying interceptors to mock response every time
  2. Can mock multiple APIs
  3. Assume support API with dynamic path variables

Gotchas to keep in mind:

  • Assume ignores Query params
  • Assume doesn’t support API's with @Url (workaround: add API endpoint in retrofit method annotation)
  • Assume is not perfect and we are working on it to make it better and easy to use. It should work with most of the endpoints and it is production safe

For any bugs or doubts raise issue & for any changes or improvements start a pull request

You might also like...
A view that makes it easy to debug response data.(一个可以方便调试响应数据的视图。)
A view that makes it easy to debug response data.(一个可以方便调试响应数据的视图。)

JSONRecyclerView 该控件可以方便调试响应数据,如下图所示: 控件的样式参考以下这个网站: JSON在线解析解析及格式化验证 项目的GitHub:JSONRecyclerView 项目Demo的GitHub:JSONRecyclerViewDemo 概述 控件是以RecyclerVie

Mocking for Kotlin/Native and Kotlin Multiplatform using the Kotlin Symbol Processing API (KSP)

Mockative Mocking for Kotlin/Native and Kotlin Multiplatform using the Kotlin Symbol Processing API (KSP). Installation Mockative uses KSP to generate

A multi-purpose library containing view injection and threading for Android using annotations
A multi-purpose library containing view injection and threading for Android using annotations

SwissKnife A multi-purpose Groovy library containing view injection and threading for Android using annotations. It's based on both ButterKnife and An

A simple library for validating user input in forms using annotations.
A simple library for validating user input in forms using annotations.

ValidationKomensky for Android A simple library for validating user input in forms using annotations. Features: Validate all views at once and show fe

HttpMocker is a simple HTTP mocking library written in Kotlin to quickly and easily handle offline modes in your apps

HttpMocker HttpMocker is a very lightweight Kotlin library that allows to mock HTTP calls relying on either OkHttp or the Ktor client libraries. It ca

mocking library for Kotlin
mocking library for Kotlin

Kotlin Academy articles Check the series of articles "Mocking is not rocket science" at Kt. Academy describing MockK from the very basics of mocking u

Most popular Mocking framework for unit tests written in Java
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

A micro mocking framework for KMP

Micro-Mock A micro Kotlin/Multiplatform Kotlin Symbol Processor that generates Mocks & Fakes. Limitations: Mocking only applies to interfaces Faking o

Mocking with Jetpack Compose - stubbing and verification of Composable functions

Mockposable A companion to mocking libraries that enables stubbing and verification of functions annotated with @androidx.compose.runtime.Composable.

Intellij Idea, Android Studio plugin for generating Kotlin data classes from JSON. Helps to avoid writing boilerplate code for model classes. Supports annotations for Gson, Moshi, Jackson.
Intellij Idea, Android Studio plugin for generating Kotlin data classes from JSON. Helps to avoid writing boilerplate code for model classes. Supports annotations for Gson, Moshi, Jackson.

JSONToKotlinClass Intellij Idea, Android Studio plugin. Plugin generates Kotlin data classes from JSON text. It can find inner classes in nested JSON.

Android library that creates app shortcuts from annotations
Android library that creates app shortcuts from annotations

Shortbread Android library that generates app shortcuts for activities and methods annotated with @Shortcut. No need to touch the manifest, create XML

This library provides advance views for lists and stacks. Some of the views are build on top of RecyclerView and others are written in their own. Annotations are compiled by annotation processor to generate bind classes. DOCS -->
This library provides advance views for lists and stacks. Some of the views are build on top of RecyclerView and others are written in their own. Annotations are compiled by annotation processor to generate bind classes. DOCS --

PlaceHolderView An advance view for lists and stacks Some Implementations Documentation You can find the PlaceHolderView documentation here which has

A simple Kotlin multi-platform abstraction around the javax.inject annotations.

Inject A simple Kotlin multi-platform abstraction around the javax.inject annotations. This allows using the annotations in Kotlin common code so that

Kotlin-native webserver for simple image annotations

Kotlin-native webserver for simple image annotations

Koin Annotations - help declare Koin definition in a very fast and intuitive way, and generate all underlying Koin DSL for you

The goal of Koin Annotations project is to help declare Koin definition in a very fast and intuitive way, and generate all underlying Koin DSL for you. The goal is to help developer experience to scale and go fast 🚀 , thanks to Kotlin Compilers.

An OkHttp interceptor which has pretty logger for request and response. +Mock support
An OkHttp interceptor which has pretty logger for request and response. +Mock support

LoggingInterceptor - Interceptor for OkHttp3 with pretty logger Usage val client = OkHttpClient.Builder() client.addInterceptor(LoggingInterceptor

LiteHttp is a simple, intelligent and flexible HTTP framework for Android. With LiteHttp you can make HTTP request with only one line of code! It could convert a java model to the parameter and rander the response JSON as a java model intelligently.

Android network framework: LiteHttp Tags : litehttp2.x-tutorials Website : http://litesuits.com QQgroup : 42960650 , 47357508 Android网络通信为啥子选 lite-htt

TART: Tracing Action Response Times

Square Tart Tracing Action Response Times! This library is not stable for usage beyond Square, the APIs and internals might change anytime. Tart... ?

A small Android project to practice executing network requests and parsing the network response
A small Android project to practice executing network requests and parsing the network response

InspirationalQuotesExercise A small Android project to practice executing network requests and parsing the network response This app uses the ZenQuote

Comments
  • Kapt is not able process .

    Kapt is not able process .

    Caused by: java.lang.NullPointerException at com.aniketbhoite.assume.processor.ProcessorUtilKt.kotlinClassMetadata(ProcessorUtil.kt:12) at com.aniketbhoite.assume.processor.AssumeProcessor.process(AssumeProcessor.kt:63) at org.jetbrains.kotlin.kapt3.base.incremental.IncrementalProcessor.process(incrementalProcessors.kt:89) at org.jetbrains.kotlin.kapt3.base.ProcessorWrapper.process(annotationProcessing.kt:166) at jdk.compiler/com.sun.tools.javac.processing.JavacProcessingEnvironment.callProcessor

    opened by tapanrgohil 2
  • Add feature to ignore assume response and get actual API response.

    Add feature to ignore assume response and get actual API response.

    Now users can ignore the Assume's response with help of ignore flag without removing @Assume annotation from their code.

    @Assume(
            responseCode = 200,
            ignore = true,
            response =
            "{\"status\":\"ok\",\"totalResults\":713,\"articles\":[]}",
        )
        @DELETE("v2/{newsId}/top-sport.json?")
        suspend fun getSport(
        ): NewsResponse
    

    The default value of ignore is false so by default Assume will return whatever you have passed as the response. Once user pass the value for ignore as true Assume will return the actual API result instead of fake one.

    enhancement 
    opened by Akashkamble 0
  • Added File Support

    Added File Support

    Now user can pass a JSON file path as the response in Assume.

    Example :

        @Assume(
            response = "/Users/nbt762/Documents/Personal/Assume/processor/src/test/kotlin/com/aniketbhoite/assume/response/response.json"
        )
        @GET("comments")
        suspend fun queryCommentsForPostId(@Query("postId") id: Int): List<CommentModel>
    
    enhancement 
    opened by Akashkamble 0
Releases(1.1)
Owner
Aniket Bhoite
Android Developer
Aniket Bhoite
mocking library for Kotlin

Kotlin Academy articles Check the series of articles "Mocking is not rocket science" at Kt. Academy describing MockK from the very basics of mocking u

MockK 4.8k Jan 3, 2023
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 micro mocking framework for KMP

Micro-Mock A micro Kotlin/Multiplatform Kotlin Symbol Processor that generates Mocks & Fakes. Limitations: Mocking only applies to interfaces Faking o

null 101 Jan 3, 2023
Android Sample Kotlin+ MVVM + Coroutines + Retrofit +Hilt+ Junit + Mockito

NTimes AppSample NY Times Most Popular Articles simple app to hit the NY Times Most Popular Articles API and show a list of articles, that shows detai

Amer Elsayed 0 Dec 27, 2021
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

thunderbiscuit 1 Jun 28, 2022
Using grpc-wiremock to mock responses in integrated tests of gRPC services

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 r

Tony A. Luz 2 Oct 28, 2021
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

mostafa elmorshdi 1 Nov 21, 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
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

Joseph James 52 Aug 15, 2022
Sandwich was invented for constructing the standardized response interface from the network response

?? A lightweight and standardized Android network response interface for handling successful data and error responses.

Jaewoong Eum 973 Jan 5, 2023