A simple project to help developers in writing their unit tests in Android Platform.

Overview

AndroidUnitTesting

codebeat badge

A simple project to help developers in writing their unit tests in Android Platform. This is not a multi-module project, but has their concepts, for example featured package represents a feature module or something like that.

Build with

MVVM Architecture descriptions

In a posts package we can represent Clean Architecture structure with data, domain and presentation folders respectively. Our view model structure is using ViewFlipper to listen/show their behaviour like show success, error, try again or empty result.

Testing Model

To write our unit tests, I used a very common approach from BDD, GivenWhenThen. In resume, given a scenario, when an action is executed, then we have a new behaviour or result.

Testing tools

The two principal external tools used here are Mockk and Truth.

Mockk has a lot of facilities for create mocks, spies, etc.

Truth same as their description a fluent tool, in my opinion is solving a Java assertion ambiguous problem: AssertThat(x, is(y)). I read different codes versions in web like tutorials, githubs, etc., with sometimes x is mock/fake result and another cases y.

Show case

Some images from this sample:

Testing Rx Results with Mocks

In a popular approach like RxJava, for testing we can just using their own tool. For example, supposing a simple method that returns a Single , like our repository, we need some steps:

  1. First mock the result of our dependency (in our case, service)
  2. Call function test from Rx library, this function will create a TestObserver
  3. Compare results: mock vs call result

In step 3, we use assertResult because internally, this function will verify if has no errors and complete the chain. Do not forget to call dispose to avoid memory leaks or flaky tests.

class PostsRepositoryImpl @Inject constructor(
    private val service: PostService
) : PostsRepository {
    override fun getPosts(): Single<List<PostResponse>> = service.getPosts()
}
// given
val posts = listOf<PostResponse>(mockk(), mockk())
every { repository.getPosts() } returns Single.just(posts)

// when
val result = repository.getPosts()

// then
result.test()
    .assertResult(posts)
    .dispose()

Testing ViewModel with LiveData

The hard part of our code.

For testing LiveData results, generally I prefer to use spies approach. In Mockk we use spyks. Basically we are listening LiveData forever and will store LiveData changes in a mutableList. In this case, capture results with Spyks.

Our steps:

  1. Create spyks to observe or capture changes in our LiveData
  2. Mock view model dependencies behaviour
  3. Observe live data changes passing spyks (item 1)
  4. Call function responsible for change LiveData value
  5. Verify if spyks are capture LiveData changes
  6. Use capture mutableList to compare values
val errorMessage: LiveData<String>
// given
val observerErrorMessage = spyk<Observer<String>>()
val errorResults = mutableListOf<String>()

// mock view model dependencies
viewModel.errorMessage.observeForever(observerErrorMessage)

// when
viewModel.takePosts()

// then
verify { observerErrorMessage.onChanged(capture(errorResults)) }
assertThat(errorResults.size).isEqualTo(1)
assertThat(errorResults.first()).isEqualTo(DEFAULT_ERROR_MESSAGE)

This example is so simple, maybe this can help someone.

API

The API used is JSONPlaceholder, the data model is Post:

[
  {
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
  },
  {
    "userId": 1,
    "id": 2,
    "title": "qui est esse",
    "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
  }
]

License

This project is licensed under the MIT License - see the LICENSE file for details

You might also like...
Easily scale your Android Instrumentation Tests across Firebase Test Lab with Flank.

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

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

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

Using grpc-wiremock to mock responses in integrated tests of gRPC services
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

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

Developers memes
Developers memes "TikTok"

Тестовое задание в Тинькофф Финтех Скриншоты Latest category Top category Приложение для просмотра gif Скролл между мемами как в тик токе Три категори

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

Owner
Bruno Gabriel dos Santos
If you're afraid to fail, then you're probably going to fail. ☕️🇧🇷
Bruno Gabriel dos Santos
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
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
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
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
Kotlin wrapper for React Test Renderer, which can be used to unit test React components in a Kotlin/JS project.

Kotlin API for React Test Renderer Kotlin wrapper for React Test Renderer, which can be used to unit test React components in a Kotlin/JS project. How

Xavier Cho 7 Jun 8, 2022
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

Robolectric 5.6k Jan 3, 2023
PowerMock is a Java framework that allows you to unit test code normally regarded as untestable.

Writing unit tests can be hard and sometimes good design has to be sacrificed for the sole purpose of testability. Often testability corresponds to go

PowerMock 3.9k Jan 5, 2023
PowerMock is a Java framework that allows you to unit test code normally regarded as untestable.

Writing unit tests can be hard and sometimes good design has to be sacrificed for the sole purpose of testability. Often testability corresponds to go

PowerMock 3.9k Jan 2, 2023
Fixtures for Kotlin providing generated values for unit testing

A tool to generate well-defined, but essentially random, input following the idea of constrained non-determinism.

Appmattus Limited 191 Dec 21, 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