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

Overview

Raccoon Logo

Raccoon

Medium Articles

Checkout these article to get more insights about this library:

Why Raccoon?

There has been different ways to mock the response from an API call, We do have a lot of good frameworks for this purpose. But, what if we need to give back a mock response according to the request and its parameters. That is what this library is all about. Raccoon is an interceptor plugin that will help the developer to mock a response back according to the request. The library uses Reflection apis under the hood to do the whole process.

Insights

The integration of this library is soo much compact in such a way that the developer doesn't need to take much time for the process. We basically need to make main 3 additions:

  • Add the Interceptor Plugin
  • Add Service class in the AndroidTest directory
  • Add Controller class and the endpoint definition in the AndroidTest directory.

Gradle

Add the following to your project's root build.gradle.kts file

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

Add the following to your project's build.gradle.kts file

dependencies {
  
  // Other dependencies
  implementation("com.github.iamjosephmj:Raccoon:1.0.5")
     
}

Basic usage

Add interceptor plugin

Retrofit

Retrofit users need to add the RaccoonOkHttpPlugin as the interceptor

  val okHttpClient = OkHttpClient.Builder()
            .addInterceptor(RaccoonOkHttpPlugin())
            .build()

  val retrofit = Retrofit.Builder()
            .client(okHttpClient)
            .build()

Adding this plugin to the real project doesn't hurt until the RaccoonStub class is initialized.

Add Controller Class

This is one of the core classes that Raccoon library is looking into. Controller class is the place were the Endpoint definitions are made. Developers can keep the logically related Endpoints in the same Controller

.buildRaccoonResponse(statusCode = 200 /* STATUS code of the api response */) } override fun tearDown() { // clean up memory. } } ">
@ControllerModule
class MockController : RaccoonController() {

    override fun setup() {
        // Do the DI related stuff
    }

    @RaccoonEndpoint(
        endpoint = "your endpoint",
        responseTime = 100, /* delay in api response delivery */
        RaccoonRequestType.GET /* user can define their request types here */
    )
    fun fetchToDoList(@Params headers: Parameters): RaccoonResponse {
        return </* Your response object */>
        .buildRaccoonResponse(statusCode = 200 /* STATUS code of the api response */)
    }


    override fun tearDown() {
        // clean up memory.
    }
}

setUp()

If user wishes to import some objects via DI, this function will be entry point to do the same. This function is called before the endpoint endpoint definition is called.

tearDown()

This function is the best candidate to free up the memory after the endpoint point definition execution. This function is called after the endpoint endpoint definition is called.

Endpoint Definition function

The user can define any names to the endpoint definition function. The only requirement that the library has is that the user should give an @RaccoonEndpoint for the same. Take the example above example to see the annotation in action.

The Endpoint Definition function has a return type RaccoonResponse. The developer can either directly create RaccoonResponse object with

    RaccoonResponse(
        statusCode=200,
        body =/* json string */ "{ ... }"
    )

or they can use the Moshi/Gson supported pojo objects. Raccoon provides a helper extension function buildRaccoonResponse to do the same

 return </* Your response object */>
        .buildRaccoonResponse(statusCode = 200 /* STATUS code of the api response */)

You can also include multiple controllers in single controller class to maintain modularity in your project.

@ControllerModule(includeControllers = [MockController2::class /* you can add any number of controllers here */])
class MockController : RaccoonController() {

    // your implementation ...
}

Take a look at the androidTest implementation to get more insights on the same.

Add Service Class

Service class helps the library to create an overall understanding about how to efficiently parse through controllers to fetch the endpoint.

@RaccoonService
class MockService : RaccoonServiceImpl() {

    @RaccoonController
    fun providesMockController() = MockController::class
}

This developer should:

  • Extend the RaccoonServiceImpl class
  • Add @RaccoonService as the annotation for the Service class.
  • Add @RaccoonController as the annotation for mock controller class provider function.

Test class implementation

@RunWith(AndroidJUnit4::class)
class MainActivityTest {

    @Before
    fun setup() {
       // setup
        RaccoonStub.setUp(
                  RaccoonConfig.Builder()
                      .addService(MockService::class)
                      .addService(MockService2::class)
                      .addService(MockService3::class)
                      .setParserType(GsonPlugin())
                      .build()
              )
        /*
         * The developer can also use {@see MoshiPlugin} as the parserType as per the project
         * requirements
         */
    }

    /**
     * You should not launch the activity before the RaccoonStub initialization.
     * There can be scenarios where the app calls the API on launch. In such cases only launch the
     * Activity inside the test function
     */
    @get:Rule
    val rule = ActivityTestRule(
        MainActivity::class.java, false, false
    )

    @Test
    fun useAppContext() {
        // run your test
    }

    @After
    fun tearDown() {
       // cleans up the memory.
        RaccoonStub.teatDown()
    }

}

Contribution, Issues or Future Ideas

If part of Raccoon is not working correctly be sure to file a Github issue. In the issue provide as many details as possible. This could include example code or the exact steps that you did so that everyone can reproduce the issue. Sample projects are always the best way :). This makes it easy for our developers or someone from the open-source community to start working!

If you have a feature idea submit an issue with a feature request or submit a pull request and we will work with you to merge it in!

Contribution guidelines

Contributions are more than welcome!

  • You should make sure that all the tests are working properly.
  • You should raise a PR to develop branch
  • Before you raise a PR please make sure your code had no issue from Android studio lint analyzer.

Please Share & Star the repository to keep me motivated.

You might also like...
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

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

Write Tests as Examples on the Method-under-test

Write Tests as Examples on the Method-under-test

Automated tests using Rest-assured with Kotlin lang
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

Setup CheckStyle, FindBugs, PMD and Lint for your Android project easily

android-quality-starter setup CheckStyle, FindBugs, PMD and Lint for your Android project easily This project adds gradle setup for quality tools ment

TestObserver to easily test LiveData and make assertions on them.
TestObserver to easily test LiveData and make assertions on them.

JCenter Update LiveData Testing is currently published on JCenter - it will serve packages until February 1st, 2022. LiveData Testing packages will be

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

Simple, lightweight, modular components to help conjure your app architecture
Simple, lightweight, modular components to help conjure your app architecture

Magic Simple, lightweight, modular components and utilities to help conjure your app architecture. Built with Kotlin coroutines to provide flexible as

Android Unit Testing Framework
Android Unit Testing Framework

Robolectric is the industry-standard unit testing framework for Android. With Robolectric, your tests run in a simulated Android environment inside a

Comments
  • Create test rule for Raccoon unit and tear down

    Create test rule for Raccoon unit and tear down

    Looking at the readme, it might be beneficial to add a junit test rule to setup and teardown Raccoon without adding the extra methods in the test class. It would also allow you to wrap the raccoon test rule around the ActivityTestRule and support launching the activity default.

    good first issue 
    opened by geoff-powell 2
Releases(1.0.7)
Owner
Joseph James
Android Developer at @cred.ai. @qburst alumini
Joseph James
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
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 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
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 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
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
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
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
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
Espresso - Use Espresso to write concise, beautiful, and reliable Android UI tests

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

Android For All 1 Jan 26, 2022